【问题标题】:telnet with pexpect lib in pythonpython中带有pexpect lib的telnet
【发布时间】:2017-10-28 21:43:54
【问题描述】:

我想在 python 中使用 pexpect lib 运行 telnet,如果 telnet 密码为真,则打印正确和错误,打印错误... 现在我的代码是:

import pexpect

ip="192.168.1.1"
password="admin"

child = pexpect.spawn("telnet "+ip+" -l admin", timeout=2)
child.expect ("Password:")
child.sendline ("admin")
child.expect(b"> ")
child.sendline ("ls")
child.close()
result = child.signalstatus
if result == 1:
    print ("Success")
else:
    print ("Bad Result")

在顶部代码中,当密码为真时,脚本运行良好并显示“成功”,但当密码错误时,脚本不显示“错误结果”,只是显示很多错误..

我该怎么做?

【问题讨论】:

    标签: python telnet pexpect


    【解决方案1】:

    当您输入错误的密码时,您并没有优雅地处理它,因此它会引发超时异常并且 child.close() 从未执行过。您看到的错误只是与异常相关的打印消息。

    解决方案: 您可以传递期望列表并相应地处理它们

    child = pexpect.spawn("telnet "+ip+" -l admin", timeout=2)
    child.expect ("Password:")
    child.sendline ("admin")
    result = child.expect(["> ", pexpect.TIMEOUT])
    if result == 0: #means prompt was caught successfully i.e. password was correct
        child.sendline ("ls")
        print ("Success")
    elif result == 1:
        print ("Bad Result")
    child.close()
    

    事实上,这可以做成一个函数,你可以根据你的用例处理更多的异常和特殊场景。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-27
      • 2018-02-04
      相关资源
      最近更新 更多