【问题标题】:pexect - unable to catch EOFpexect - 无法捕获 EOF
【发布时间】:2021-08-06 23:01:30
【问题描述】:

我无法获得 pexpect 的 EOF 输出。

import pexpect

session = pexpect.spawn('scp -C -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -r /tmp/test abcuser@x.x.x.x:/tmp', encoding='utf-8')
session.expect(pexpect.EOF, timeout=None)

[CTRL + C] - 等了很久

^CTraceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3/dist-packages/pexpect/spawnbase.py", line 340, in expect
    return self.expect_list(compiled_pattern_list,
  File "/usr/lib/python3/dist-packages/pexpect/spawnbase.py", line 369, in expect_list
    return exp.expect_loop(timeout)
  File "/usr/lib/python3/dist-packages/pexpect/expect.py", line 111, in expect_loop
    incoming = spawn.read_nonblocking(spawn.maxread, timeout)
  File "/usr/lib/python3/dist-packages/pexpect/pty_spawn.py", line 470, in read_nonblocking
    r, w, e = select_ignore_interrupts(
  File "/usr/lib/python3/dist-packages/pexpect/utils.py", line 143, in select_ignore_interrupts
    return select.select(iwtd, owtd, ewtd, timeout)
KeyboardInterrupt

【问题讨论】:

  • 也许scp 正在提问并等待输入。
  • 您可以导入 sys,然后将 logfile=sys.stdout 添加到 spawn 调用以查看 pexpect 记录的内容。
  • 看起来当它询问密码时它只是等待,所以没有显示 EOF,但是当我之后执行 session.sendline 时,它​​显示 0 ......所以认为这很好。谢谢大家的建议。

标签: python python-3.x expect pexpect


【解决方案1】:

我使用两个虚拟机建立了一个快速的内部网络,当我在提示符下运行scp 命令时,我看到了:

Warning: Permanently added '192.168.56.101' (RSA) to the list of known hosts.
abcuser@192.168.56.101's password: 

为了提供密码(如果被要求)并获得您的反馈,我会将代码修改为:

import pexpect
from getpass import getpass

session = pexpect.spawn(
    "scp -C -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -r /tmp/test abcuser@192.168.56.101:/tmp",
    encoding="utf-8")
     
# EOF = Command finished executing and the child is closed
index = session.expect_exact(["password:", pexpect.EOF])

# First feedback
print(str(session.before) + str(session.match) + "\n")

if index == 0:
    password = getpass()
    session.sendline(password)
    session.expect_exact(pexpect.EOF)

# Final feedback; the match is EOF and there is nothing after that
print(str(session.before))

# The child is already closed, but just in case
session.close()

输出

Warning: Permanently added '192.168.56.101' (RSA) to the list of known hosts.
abcuser@192.168.56.101's password:

Password: 
 
test                                          100%   16    36.7KB/s   00:00

我会避免将timeout 设置为None。使用默认的 30 秒或为较大的文件设置合理的时间限制。

希望这就是您想要的。祝你编码好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2012-08-08
    • 2012-11-09
    • 2011-03-14
    • 2012-03-15
    • 2014-11-25
    相关资源
    最近更新 更多