Improve productivity by using the expect tool with the shell to automate the ability to back up switch configurations.
Software: expect-5.44.1.15-4.el6.i686
Purpose: By reading the contents of the file, automatically log in to the network device, complete the corresponding command, and finally read the configuration information, save as a file.
Here's the code:
1, main.sh #通过shell脚本来实现对文件内容的读取, and call expect script to complete the device configuration read and save.
#!/bin/bash
For line in ' Cat/tmp/hosts.txt ' #逐行读取hosts文件内容
Do
Server= ' echo $line |awk-f | ' {print '} '
Login= ' echo $line |awk-f | ' {print $} '
Passwd= ' echo $line |awk-f | ' {print $} '
Enpasswd= ' echo $line |awk-f | ' {Print $4} '
./get_switch_conf.exp $server $login $passwd $enpasswd
Sleep 3
Done
2, Get_switch_conf.exp #通过expect脚本来完成自动登录设备, read information, save information.
#!/usr/bin/expect-f
if {$ARGC! = 4} {
Send_user "Usage: $argv 0 <server> <login> <password> <enpassword>\n"
Exit
}
Set timeout 1
Set term ANSI
Set SERVER [lindex $argv 0]
Set LOGIN [lindex $argv 1]
Set PASSWD [lindex $argv 2]
Set ENPASSWD [lindex $argv 3]
Spawn Telnet
Expect "telnet>"
Send "open $SERVER \ r"
Sleep 10
Expect "Login:"
Send "$LOGIN \ r"
Sleep 1
Expect "Password:"
Send "$PASSWD \ r"
Sleep 1
Expect "*>"
Send "en\r"
Sleep 1
Expect "Password:"
Send "$ENPASSWD \ r"
Sleep 1
Expect "*#"
Log_file/var/log/[clock format [clock seconds]-format "%y-%m-%d"]. $SERVER. log #生成文件, format +ip by Time
Send "show run\r"
while (1) {
Sleep 1
Expect {
"--more--" {Send "}"
"*#" {break}
}
}
Send "exit\r"
Interact
3, Host.txt
10.207.*.*|admin|password|enpassword
10.207.*.*|admin|password|enpassword
This article from "Lifelong Learning" blog, reproduced please contact the author!
Batch automatic backup switch configuration using expect