【问题标题】:python pexpect - not taking the expect outputpython pexpect - 不接受期望输出
【发布时间】:2013-08-14 04:29:34
【问题描述】:

我正在使用 pepexpect 登录路由器。我这样做的方法是登录到 linux 服务器,然后登录到路由器。

usr = 'myusername'
pwd='mypwd'
child.sendline('ssh -o StrictHostKeyChecking=no -l '+usr+' '+ip)
index = child.expect(['assword:', pexpect.EOF,pexpect.TIMEOUT])

当我手动登录路由器时,我得到以下信息:

WARNING NOTICE: This is a private system. The actual or attempted, unauthorized
access, use or modification of this system is strictly prohibited.
Individuals undertaking such unauthorized access, use or modification are
subject to company disciplinary proceedings and/or criminal and civil penalties
under applicable domestic and foreign laws. The use of this system may be
monitored and recorded for administrative and security reasons in accordance
with local law. If such monitoring and/or recording reveals possible evidence
of criminal activity, the results of such monitoring may be provided to law
enforcement officials. Continued use of this system after receipt of this
notice constitutes consent to such security monitoring and recording.
!
Global Baseline Configuration:  v1.0

Cisco Wide Area Application Engine

username@10.58.218.237's password: 

即使密码在输出中,索引结果也是 2 = pexpect.TIMEOUT 我的脚本在其他路由器上工作,但我不知道为什么不能在这个路由器上工作。谢谢

【问题讨论】:

  • 你确定你的意思是assword
  • 是的,assword 适用于 Password 和 password。
  • 您确定密码提示来自远程服务器而不是您用于登录的软件,并且即使服务器认为它正在与脚本对话,它也会发送提示?
  • 我对这个问题的提示来自思科路由器。

标签: python pexpect


【解决方案1】:

我很难使用 pexpect 来填充提示,但我设法写了一些有用的东西:

def call_and_type(command, prompt_regex, entry):
    p = pexpect.spawn(command, logfile=sys.stdout, maxread=16384)
    index = p.expect_exact([prompt_regex, pexpect.EOF])
    if index == 0:
        p.setecho(False)
        p.sendline(entry)
        while p.read():
            pass

【讨论】:

  • 我添加了 maxread=16384 仍然有问题。有没有办法在发送命令时查看 pexpect 看到的内容?
  • 我认为您应该首先在 shell 中尝试我的代码,例如 command = "sudo apt-get update"entry = "wrong password"。此代码应将所有内容输出到标准输出。
  • 我的代码不是问题,问题是我的代码,但我能够通过 logfile=sys.我遇到的问题是我在设备列表上运行我的脚本。在其中一个设备上,我遇到了列表中下一个站点的新问题,因为我没有发现新问题。谢谢