shell结合expect 脚本自动备份华为交换机配置文件

时间:2022-11-03 15:59:33

最近看了点expect的知识点,就产生了个利用它来自动备份交换机配置的想法。于是就做了下尝试。 来看看如何实现。

Expect是一个用来实现自动交互功能的软件套件,是基于TCL的脚本编程工具语言。

  • 找了台CentOS 7的机器,先安装expect。

    yum install expect -y

  • 找了台windows,运行tftp-server。

shell结合expect 脚本自动备份华为交换机配置文件

  • 手动创建了2个以交换机IP为名字的目录,用来存放对应各自的配置文件。 shell结合expect 脚本自动备份华为交换机配置文件

  • 脚本介绍

脚本有2个,一个是shell脚本,一个是expect脚本,一个文本文件。 shell结合expect 脚本自动备份华为交换机配置文件

文本文件: 存储设备的IP地址,一行一个。 expect脚本: 实现交换机交互式登陆和操作。 shell脚本: 操作文本文件并传参给expect脚本。

  • 脚本内容 [root@localhost scripts]# cat auto_backup.sh
#!/bin/bash

dateinfo=`date +"%Y%m%d"`
for ip in `cat ./iplist`
do    
   /usr/bin/expect  /root/scripts/auto_backup.exp $ip $dateinfo
done

[root@localhost scripts]# cat auto_backup.exp

#!/usr/bin/expect

set ip [lindex $argv 0]
set dateinfo [lindex $argv 1]
set username "admin"
set password "xyz!\@#\$123"  #特殊字符需要转义
set tftpsvr "10.1.11.241"


spawn telnet $ip

expect {
    "*Username" {send "$username\n";exp_continue }
    "*Password" {send "$password\n"; exp_continue }
    ">"         {send "tftp $tftpsvr put vrpcfg.zip $ip\\$ip-vrpcfg-$dateinfo.zip\n" }
}

expect ">" {send "quit\n"}
expect eof


[root@localhost scripts]# cat iplist

10.1.3.1
10.1.3.11

  • 执行sh脚本:

shell结合expect 脚本自动备份华为交换机配置文件

shell结合expect 脚本自动备份华为交换机配置文件

  • 查看tftp-server上传结果

shell结合expect 脚本自动备份华为交换机配置文件

这样我们就可以通过cron来定期备份了。 其他品牌的网络设备对exp脚本略作修改即可。