如何使用Expect自动化Telnet会话?

8
我正在尝试编写一个expect脚本来自动化telnet。这是我目前的代码。
#!/usr/bin/expect
# Test expect script to telnet.

spawn telnet 10.62.136.252
expect "foobox login:"
send "foo1\r"
expect "Password:"
send "foo2\r"
send "echo HELLO WORLD\r"
# end of expect script.

基本上,我想做的是telnet到以下IP地址,然后回显HELLO WORLD。然而,在尝试telnet之后,脚本似乎失败了...我不确定它能否接受登录和密码输入,但它没有回显HELLO WORLD。相反,我只得到这个输出:

cheungj@sfgpws30:~/justin> ./hpuxrama 
spawn telnet 10.62.136.252
Trying 10.62.136.252...
Connected to 10.62.136.252.
Escape character is '^]'.
Welcome to openSUSE 11.1 - Kernel 2.6.27.7-9-pae (7).

foobox login: foo1
Password: foo2~/justin> 
4个回答

7
很难确定,但从你粘贴的输出来看,可能是以下情况之一:
  1. 你的脚本在发送下一个命令之前没有等待登录完成。
  2. 你的脚本在你能看到任何输出之前退出并关闭了进程。
生活中没有保证,但作为第一步,我建议尝试这个方法:
#!/usr/bin/expect -f

spawn telnet 10.62.136.252
expect "foobox login:"
send "foo1\r"
expect "Password:"
send "foo2\r"

# Wait for a prompt. Adjust as needed to match the expected prompt.
expect "justin>"
send "echo HELLO WORLD\r"

# Wait 5 seconds before exiting script and closing all processes.
sleep 5

替代方案

如果手动编写脚本无法使其正常工作,可以尝试使用Expect自带的autoexpect脚本。您可以手动执行命令,autoexpect会根据这些命令生成一个基于Expect的typescript,您可以根据需要进行编辑。

这是找出Expect实际看到的内容的好方法,特别是在问题难以确定的情况下。多年来,它为我节省了大量的调试时间,并且如果上述解决方案不适用于您,则绝对值得一试。


5
您发送了echo命令,但在预期提示之前。请尝试:
# after sending the password
expect -re "> ?$"
send "echo HELLO WORLD\r"
expect eof

1

0

这是一个简化版本

#!/usr/bin/expect
# just do a chmod 755 one the script
# ./YOUR_SCRIPT_NAME.sh $YOUHOST $PORT
# if you get "Escape character is '^]'" as the output it means got connected otherwise it has failed

set ip [lindex $argv 0]
set port [lindex $argv 1]

set timeout 5
spawn telnet $ip $port
expect "'^]'."

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接