尝试让GPT用rust语言编写交换机自动备份配置文件成功

经过上次GPT编写python的脚本语言备份交换机配置文件成功之后,我想起了rust,因为这个rust我也只会hello world,于是我就让GPT去生成rust代码,复制粘贴到vscode中,居然也成功了,而且速度比python还快。绝了。

以下是交换机的批量备份,备份速度很快。

以下是GPT代码:

GPT还不是100%的正确,比如telnet这里需要修改0.2.1的版本,因为crate里没有0.9的版本

[dependencies]
telnet = "0.2.1"
chrono = "0.4"
use std::fs::{self, File};
use std::io::{self, BufRead, BufReader, Write, BufWriter};
use std::thread::sleep;
use std::time::Duration;
use telnet::{Telnet, Event};
use chrono::Local;

fn main() -> io::Result<()> {
    let username = "交换机用户名";
    let password = "交换机密码";
    let input_file_path = "ip.txt";
    let output_dir = "写本地自己要备份的路径";

    let ip_list = read_ip_list(input_file_path)?;
    for ip in ip_list {
        println!("Processing IP: {}", ip);
        match backup_switch_config(&ip, username, password, output_dir) {
            Ok(_) => println!("Backup for {} successful", ip),
            Err(e) => println!("Backup for {} failed: {}", ip, e),
        }
    }
    Ok(())
}

fn read_ip_list(file_path: &str) -> io::Result<Vec<String>> {
    let file = File::open(file_path)?;
    let reader = BufReader::new(file);
    let mut ip_list = Vec::new();
    for line in reader.lines() {
        let ip = line?.trim().to_string();
        if !ip.is_empty() {
            ip_list.push(ip);
        }
    }
    Ok(ip_list)
}

fn backup_switch_config(ip: &str, username: &str, password: &str, output_dir: &str) -> io::Result<()> {
    let port = 23;

    // 连接到交换机
    let mut connection = Telnet::connect((ip, port), 256)?;

    // 登录过程
    login(&mut connection, username, password)?;

    // 发送命令禁用分屏显示
    connection.write(b"screen-length disable\n")?;
    wait_for_prompt(&mut connection)?;

    // 发送命令获取配置文件
    connection.write(b"display current-configuration\n")?;

    // 获取配置文件
    let config = get_configuration(&mut connection)?;

    // 构建文件路径和文件名
    let now = Local::now();
    let formatted_time = now.format("%Y-%m-%d_%H-%M-%S").to_string();
    let file_path = format!(
        "{}config_{}_{}.txt",
        output_dir, ip, formatted_time
    );

    // 保存配置文件
    save_to_file(&file_path, &config)?;

    println!("配置文件已成功保存到: {}", file_path);

    Ok(())
}

// 登录函数
fn login(connection: &mut Telnet, username: &str, password: &str) -> io::Result<()> {
    loop {
        match connection.read()? {
            Event::Data(buffer) => {
                let data = String::from_utf8_lossy(&buffer);
                print!("{}", data);

                if data.contains("Username:") {
                    connection.write(format!("{}\n", username).as_bytes())?;
                } else if data.contains("Password:") {
                    connection.write(format!("{}\n", password).as_bytes())?;
                } else if data.contains(">") || data.contains("#") {
                    println!("Telnet 登录成功!");
                    break;
                }
            }
            _ => {}
        }
    }
    Ok(())
}

// 等待提示符函数
fn wait_for_prompt(connection: &mut Telnet) -> io::Result<()> {
    loop {
        match connection.read()? {
            Event::Data(buffer) => {
                let data = String::from_utf8_lossy(&buffer);
                print!("{}", data);
                if data.contains(">") || data.contains("#") {
                    break;
                }
            }
            _ => {}
        }
    }
    Ok(())
}

// 获取配置文件函数
fn get_configuration(connection: &mut Telnet) -> io::Result<String> {
    let mut config = String::new();
    loop {
        match connection.read()? {
            Event::Data(buffer) => {
                let data = String::from_utf8_lossy(&buffer);
                print!("{}", data);
                config.push_str(&data);
                if data.contains("return") {
                    break;
                }
            }
            _ => {}
        }
    }
    Ok(config)
}

// 保存配置文件函数
fn save_to_file(file_path: &str, config: &str) -> io::Result<()> {
    let file = File::create(file_path)?;
    let mut writer = BufWriter::new(file);

    for line in config.lines() {
        if !line.trim().is_empty() {
            writeln!(writer, "{}", line)?;
        }
    }

    Ok(())
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值