zl程序教程

您现在的位置是:首页 >  系统

当前栏目

Linux之使用expect备份华为交换机配置

Linux备份配置华为 交换机 expect 使用
2023-09-14 09:13:17 时间

一、expect简介

  expect一个自动化交互的软件,expect基于tcl脚本,expect脚本的运行需要tcl的支持。expect对一些需要交互输入的命令很有帮助,比如ssh ftp scp telnet。expect对于通过服务器批量管理交换机尤其有用,本示例以使用expect备份华为交换机配置。

二、expect安装

[root@test1 scripts]# yum install -y expect

Installed:
expect.x86_64 0:5.45-14.el7_1

Dependency Installed:
tcl.x86_64 1:8.5.13-8.el7

Complete!

三、备份脚本

1、编写备份脚本

[root@test1 scripts]# vim backup_switch_conf.sh
脚本内容如下

#!/usr/bin/expect -f 
 set ip [lindex $argv 0 ]   
 set username [lindex $argv 1 ]   
 set password [lindex $argv 2 ]  
 set superpassword [lindex $argv 3 ] 
 set timeout 30         
 spawn ssh -l $username $ip
 expect "*assword:"
 send "$password\r"
 expect "*>"
 send "display current-configuration\r"
 expect {
 "*More ----" { send " " ; exp_continue }
 }

expect "*>"
send "quit\r"
expect eof

2、脚本授权

[root@test1 scripts]# chmod u+x backup_switch_conf.sh

四、备份演示

  使用./backup_switch_conf.sh ip username password备份指定交换机的配置

在这里插入图片描述
查看备份后的配置
[root@test1 scripts]# ll -h
total 16K
-rwxr–r-- 1 root root 397 Mar 23 16:22 backup_switch_conf.sh
-rw-r–r-- 1 root root 8.1K Mar 23 16:25 switch.conf
在这里插入图片描述

五、expect主要命令

  • spawn 新建一个进程,这个进程的交互由expect控制
  • expect 等待接受进程返回的字符串,直到超时时间,根据规则决定下一步操作
  • send 发送字符串给expect控制的进程
  • set 设定变量为某个值
  • exp_continue 重新执行expect命令分支
  • [lindex $argv 0] 获取expect脚本的第1个参数
  • [lindex $argv 1] 获取expect脚本的第2个参数
  • set timeout -1 设置超时方式为永远等待
  • set timeout 30 设置超时时间为30秒
  • interact 将脚本的控制权交给用户,用户可继续输入命令
  • expect eof 等待spawn进程结束后退出信号eof