为什么 pxssh.before 在与 py.test 一起使用时表现不同?

why pxssh.before behaves different when used with py.test.?

from pexpect import pxssh
import getpass
import time
import sys
s=pxssh.pxssh()

class Testinstall:

    def setup_class(cls):
        cls.s=pxssh.pxssh()
        cls.s.login('10.10.62.253', 'User','PW',auto_prompt_reset=False)

    def teardown_class(cls):
        cls.s.logout()

    def test_cleanup(cls):
        cls.s.sendline('cat test.py')
        cls.s.prompt(timeout=10)
        cls.s.sendline('cat profiles.conf')
        cls.s.prompt(timeout=10)
        print('s.before')
        print (cls.s.before)
        print('s.after')
        print(cls.s.after)

在上面的代码中,print(cls.s.before) 打印了两个 cat 命令的输出。 按照预期,它应该只打印第二个 cat 命令的输出,即 cat profiles.conf。 当在 shell 的 python 会话中尝试时,它仅显示第二个 cat 命令的输出(按照预期)

如果对 pxssh.login() 使用 auto_prompt_reset=False,则不能使用 pxssh.prompt()。根据文档:

pxssh uses a unique prompt in the prompt() method. If the original prompt is not reset then this will disable the prompt() method unless you manually set the PROMPT attribute.

因此,对于您的代码,prompt() 都会超时,.before 会有所有输出,.after 会是 pexpect.exceptions.TIMEOUT


文档还说

Calling prompt() will erase the contents of the before attribute even if no prompt is ever matched.

但根据我的测试,这不是真的:

>>> from pexpect import pxssh
>>> ssh = pxssh.pxssh()
>>> ssh.login('127.0.0.1', 'root', 'passwd')
True
>>> ssh.PROMPT = 'not-the-real-prompt'
>>> ssh.sendline('hello')
6
>>> ssh.prompt(timeout=1)
False
>>> ssh.before
'hello\r\n-bash: hello: command not found\r\n[PEXPECT]# '
>>> ssh.after
<class 'pexpect.exceptions.TIMEOUT'>
>>> ssh.sendline('world')
6
>>> ssh.prompt(timeout=1)
False
>>> ssh.before
'hello\r\n-bash: hello: command not found\r\n[PEXPECT]# world\r\n-bash: world: command not found\r\n[PEXPECT]# '
>>> ssh.after
<class 'pexpect.exceptions.TIMEOUT'>
>>>

从结果可以看出 .before 没有被第二个 prompt() 擦除。相反,它附加了新的输出。

您可以使用 ssh.sync_original_prompt() 而不是 ssh.prompt()。