我是这个社区以及编程的新手。我目前正在研究一个简单的Expect脚本,该脚本可读取包含DNS名称列表的文件,将SSH读入Cisco路由器,并执行简单的“ show ip int brief”。
此列表包含当前无法访问的一些主机,因此我试图使脚本使该无法访问的设备超时,但继续使用其余设备。
运行脚本时,它可以SSH到第一台设备并执行“ show”命令。但是,当它到达第二个设备(无法访问)时,它将在此处挂起大约30秒钟,然后终止脚本。我不确定自己在做什么错。任何帮助将不胜感激。
#!/usr/bin/expect
#
#
set workingdir cisco/rtr
puts stdout "Enter TACACS Username:"
gets stdin tacuserid
system stty -echo
puts stdout "Enter TACACS password:"
gets stdin tacpswd
puts stdout "\nEnter enable password:"
gets stdin enabpswd
system stty echo
#
set RTR [open "$workingdir/IP-List.txt" r]
set timestamp [timestamp -format %Y-%m-%d_%H:%M]
#
while {[gets $RTR dnsname] != -1} {
if {[ string range $dnsname 0 0 ] != "#"} {
send_user "The value of the router name is $dnsname\n"
set timeout 10
set count 0
log_file -a -noappend $workingdir/session_$dnsname\_$timestamp.log
send_log "### /START-SSH-SESSION/ IP: $dnsname @ [exec date] ###\n"
spawn ssh -o StrictHostKeyChecking=no -l $tacuserid $dnsname
expect {
"TACACS Password: " {send "$tacpswd\r"}
timeout {puts "$dnsname - failed to login"; wait;close;exp_continue}
}
expect {
{>} {send "enable\r"; send_user "on the second expect\n"}
}
expect {
{assword: } {send "$enabpswd\r"}
}
#
expect {
"#" {send "show ip int brief\r"}
}
#expect "#"
send "exit\r"
send_log "\n"
send_log "### /END-SSH-SESSION/ IP: $dnsname @ [exec date] ###\n"
log_file
}
}
exit
答案 0 :(得分:0)
您的第一个期望正在做
expect {...
timeout {puts "..."; wait; close; exp_continue}
}
当ssh
花费10秒以上的时间连接到主机时,这将匹配。
当匹配时,它不可避免地退出并出现错误( spawn id ... not open )。这是因为您等待命令结束,关闭生成连接,然后重新启动相同的Expect命令。
您可能打算使用continue
而不是exp_continue
,以便继续进行封闭的while
循环。