如何使用Expect自动进行telnet会话? [英] How to automate telnet session using Expect?

查看:486
本文介绍了如何使用Expect自动进行telnet会话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个期望脚本来自动执行telnet.这就是我到目前为止所拥有的.

I'm trying to write an expect script to automate telnet. This is what I have so far.

#!/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.相反,我只是得到以下输出:

Basically, what I want to do is telnet to the following IP address and then echo HELLO WORLD. However, it seems that the script fails after attempting to telnet...I'm not sure if it's able to accept login and password input, but it is not echoing HELLO WORLD. Instead, I just get this output:

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> 

推荐答案

很难说,但是从输出中粘贴出来的样子:

It's hard to tell, but from the output you're pasting it looks like:

  1. 您的脚本在发送下一个命令之前不等待登录完成.
  2. 您的脚本正在退出并关闭该过程,然后才能看到任何输出.

生活中没有保证,但我会首先尝试这样做:

There are no guarantees in life, but I'd try this as a first step:

#!/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脚本.您可以手动执行命令,并且自动期望将基于这些命令生成Expect打字稿,然后可以根据需要进行编辑.

Alternatives

If you can't get your script to work by manually programming it, try the autoexpect script that comes with Expect. You can perform your commands manually, and autoexpect will generate an Expect typescript based on those commands, which you can then edit as needed.

这是找出Expect实际看到的内容的好方法,尤其是在难以确定问题的情况下.多年来,这为我节省了很多调试时间,如果上面的解决方案对您不起作用,绝对值得一试.

It's a good way to find out what Expect actually sees, especially in cases where the problem is hard to pin down. It's saves me a lot of debugging time over the years, and is definitely worth a try if the solution above doesn't work for you.

这篇关于如何使用Expect自动进行telnet会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆