Linux Expect 自動化套件
安裝Expect
apt install expect
使用範例
自動telnet登入
建立telnet_expect.sh
#!/usr/bin/expect
set username "test"
set password "test123"
set command "use command"
spawn telnet $ip
expect {
"*ogin:" {
send "$username\r"
expect "*assword:"
send "$password\r"
expect ">"
send "$command\r"
expect ">"
send "exit\r"
}
}
chmod +x telnet_expect.sh
多台設備多線程自動登入
建立設備清單,建立ip.txt
device_a*192.168.0.1
device_b*192.168.0.2
device_c*192.168.0.3
建立多線程腳本telnet.sh,創建log資料夾儲存log
#!/bin/bash
rm log/*
for i in `cat ip.txt`
do {
substr=$(echo $i | cut -d"*" -f 2)
kip=$substr
substr=$(echo $i | cut -d"*" -f 1)
kname=$substr
/usr/bin/expect expect.sh $kip $kname
}&
done
wait
建立expect.sh
#!/usr/bin/expect
set timeout 30
set username "test"
set password "test123"
set command "show configuration |display set|no-more"
set date [ clock format [ clock seconds ] -format "%Y%m%d" ]
set kip [lindex $argv 0]
set kname [lindex $argv 1]
spawn telnet $kip
log_file "log/$date-${kname}.log"
expect {
"*ogin:" {
send "$username\r"
expect "*assword:"
send "$password\r"
expect ">"
send "set cli timestamp\r"
expect ">"
send "$command\r"
expect ">"
send "exit\r"
log_file
}
}
chmod +x expect.sh
執行telnet.sh
No comments to display
No comments to display