11

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

 1 year ago
source link: https://blog.51cto.com/magic3/5819445
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

精选 原创

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

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

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

    yum install expect -y

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

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

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

文本文件: 存储设备的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 脚本自动备份华为交换机配置文件_网络自动化_04
shell结合expect 脚本自动备份华为交换机配置文件_shell_05
  • 查看tftp-server上传结果
shell结合expect 脚本自动备份华为交换机配置文件_网络自动化_06

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

Linux 下的tftp-server也可以,但是exp脚本中就不能指定备份的目录了,只能备份到tftp-server的根目录下。Linux会将指定目录时的""当作普通字符写在文件名中。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK