【问题标题】:How to automate telnet session using Expect?如何使用 Expect 自动化 telnet 会话?
【发布时间】:2023-04-01 12:33:01
【问题描述】:

我正在尝试编写一个期望脚本来自动化远程登录。这是我目前所拥有的。

#!/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。但是,似乎脚本在尝试远程登录后失败了......我不确定它是否能够接受登录名和密码输入,但它没有回显 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> 

【问题讨论】:

    标签: linux telnet expect


    【解决方案1】:

    很难说,但从您粘贴的输出来看,它看起来像:

    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 打字稿,然后您可以根据需要对其进行编辑。

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

    【讨论】:

      【解决方案2】:

      您发送echo 命令时并没有事先期待提示。试试:

      # after sending the password
      expect -re "> ?$"
      send "echo HELLO WORLD\r"
      expect eof
      

      【讨论】:

        【解决方案3】:

        你见过this StackOverflow Question吗?

        他似乎通过使用花括号使事情变得有效。

        【讨论】:

          【解决方案4】:

          这里是简化版

          #!/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 "'^]'."
          

          【讨论】:

            猜你喜欢
            • 2014-08-13
            • 2011-08-21
            • 2013-07-10
            • 2013-09-03
            • 2011-02-07
            • 2012-04-01
            • 1970-01-01
            • 2017-08-29
            • 2011-01-04
            相关资源
            最近更新 更多