【问题标题】:Handling telnet timeout/connection refused in pexpect python router在 pexpect python 路由器中处理 telnet 超时/连接被拒绝
【发布时间】:2017-02-12 06:07:34
【问题描述】:

我正在尝试编写一个脚本,我需要 ssh 多个跳转服务器来访问路由器。

例如LocalMachine----ssh---server1---ssh---server2---telnet/ssh---路由器

不确定最好的方法是什么,我尝试通过 pexpect 实现它。 我的要求是当我从服务器 server2 远程登录到路由器并且它超时/连接被拒绝时我想尝试 ssh 请问有什么建议吗?

import time, pexpect

child = pexpect.spawn('ssh username@server-1')   ##########ssh to 1st Jump server
child.expect('password: ')
child.sendline('abc')
child.expect('$')
child.sendline('ssh username@server-2')   ##########ssh to 2nd Jump server
print child.before
child.expect('password:')
child.sendline('xyz')
child.expect('$')
print child.before
host=raw_input("Enter Router name: ")    

try:
    print "Trying Telnet ", host
    child.sendline(' telnet ' + host)  ### router telnet at this point i want if telnet is timeout/connection refused try ssh
    print child.before
except pexpect.TIMEOUT: 
    print child.before
else:
    child.expect(':')
    child.sendline("User")
    child.expect(":")
    child.sendline('passwprd')
    child.expect('#')
    child.sendline("\n")
    child.expect("#")
finally:
    print "Trying SSH ", host
    child.sendline(' ssh -l User ' + host)
    print child.before
    child.expect(":")
    child.sendline('password')
    child.expect('#')
    child.sendline("\n")

print child.before
child.interact()

【问题讨论】:

    标签: python-2.7 pexpect


    【解决方案1】:

    pexpect.TIMEOUT 异常将由您机器上运行的程序实例引发。它不知道在您已通过 ssh 连接到的远程计算机上运行的 telnet 实例是否超时。您可以查看 telnet 连接是否有超时或类似错误的唯一方法,即。连接被拒绝,就是通过pexpect查看进程的输出。如果您查看documentation 中的expect,它表示您可以提供条件列表 - 这可能是一种方法。

    例如:

    index = p.expect (['timeout', 'connection refused])  # Fill in correct words :)
    

    【讨论】:

    • 尝试使用下面的值,但如果 i 始终为 "$" .. 错误是什么? i = child.expect(["用户名:","$", "你确定要继续连接吗(是/否)?","密码:",">"])
    猜你喜欢
    • 2015-06-03
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 2014-01-06
    • 1970-01-01
    相关资源
    最近更新 更多