我正在使用Expect脚本从我的主机提取configuration信息。
问题是我的一些主机(当inputenable命令时)会提示inputlogin名和密码。 这大部分是较老的惠普套件,但我也在其他地方碰到过。
如果是合法的语法,像下面这样的嵌套expect语句就可以做到这一点。 我怎样才能做到这一点?
expect { default { send_user "\nEnable Mode Failed - Check Password\n"; exit 1 } "*\#" {} "*>" { send "enable\n" expect{ "Login" { send "$username\n" } default {} } expect "*assword" send "$enablepassword\n" expect "*\#" } }
我知道我只有轻微的语法 – 我已经看到很多引用,描述使用嵌套期望 – 但对于我的生活,我不能完全得到它。
你可以这样写:
exp_internal 1 expect { default { send_user "\nEnable Mode Failed - Check Password\n"; exit 1 } "*>" { send "enable\r" expect{ "Login" { send "$username\r" exp_continue } "*assword" { send "$enablepassword\r" } } # Now, look back to the outer expect to continue expecting the "#" prompt exp_continue } "*#" }
exp_internal 1来启用debugging \r终止send命令(回车是“按回车”) exp_continue在包含内循环expect继续寻找其他模式。 非常感谢Glenn,我有一个脚本,可以让我从任何思科或HP设备上获取信息。
#!/usr/bin/expect -f set hostname [lindex $argv 0]; set username [lindex $argv 1]; set password [lindex $argv 2]; set enablepassword [lindex $argv 3]; spawn ssh -o StrictHostKeyChecking=no $username\@$hostname expect { timeout { send_user "\nTimeout Exceeded - Check Host\n"; exit 1 } eof { send_user "\nSSH Connection To $hostname Failed\n"; exit 1 } "*\#" {} "*assword:" { send "$password\n" } } # This allows for handling any of the various HP login screens. sleep 5 send " " sleep 5 send "3\n" sleep 5 expect { "*>" { send "enable\n" expect { "*ogin" { send "$username\n" } } expect { "*assword" { send "$enablepassword\n" exp_continue } exp_continue } } "*\#" {} default { send_user "\nEnable Mode Failed - Check Password\n"; exit 1 } } # Disable paging. This is both the HP and Cisco statements. send "terminal length 0\n" send "no page\n" expect "*\\#" log_file -noappend ./$hostname send "show run\n" expect "#\n" log_file send "end\n" expect "\#" expect "\#" send "exit\n" expect ":~\$" exit