python - Windows 替代预期

标签 python windows command-line-interface pexpect

我正在尝试编写一个运行特定命令的跨平台工具,期望特定输出以进行验证,并发送特定输出(如用户名/密码)以进行身份​​验证。

在 Unix 上,我成功地编写了一个使用 pexpect 库的 Python 工具(通过 pip install pexpect)。这段代码工作完美,正是我想要做的。我在下面提供了一小段用于概念验证的代码:

self.process = pexpect.spawn('/usr/bin/ctf', env={'HOME':expanduser('~')}, timeout=5)
self.process.expect(self.PROMPT)
self.process.sendline('connect to %s' % server)
sw = self.process.expect(['ERROR', 'Username:', 'Connected to (.*) as (.*)'])
if sw == 0:
    pass
elif sw == 1:
    asked_for_pw = self.process.expect([pexpect.TIMEOUT, 'Password:'])
    if not asked_for_pw:
        self.process.sendline(user)
        self.process.expect('Password:')
    self.process.sendline(passwd)
    success = self.process.expect(['Password:', self.PROMPT])
    if not success:
        self.process.close()
        raise CTFError('Invalid password')
elif sw == 2:
    self.server = self.process.match.groups()[0]
    self.user = self.process.match.groups()[1].strip()
else:
    info('Could not match any strings, trying to get server and user')
    self.server = self.process.match.groups()[0]
    self.user = self.process.match.groups()[1].strip()
info('Connected to %s as %s' % (self.server, self.user))

我尝试在 Windows 上运行相同的源代码(将 /usr/bin/ctf 更改为 c:/ctf.exe),但我收到一条错误消息:

Traceback (most recent call last):
  File ".git/hooks/commit-msg", line 49, in <module> with pyctf.CTFClient() as c:
  File "C:\git-hooktest\.git\hooks\pyctf.py", line 49, in __init__
    self.process = pexpect.spawn('c:/ctf.exe', env={'HOME':expanduser('~')}, timeout=5)
  AttributeError: 'module' object has no attribute 'spawn'

根据预期 documentation :

pexpect.spawn and pexpect.run() are not available on Windows, as they rely on Unix pseudoterminals (ptys). Cross platform code must not use these.

这让我开始寻找 Windows 的等价物。我尝试了流行的 winpexpect 项目 here甚至更新的( fork 的)版本 here ,但这些项目似乎都不起作用。我使用的方法:

self.process = winpexpect.winspawn('c:/ctf.exe', env={'HOME':expanduser('~')}, timeout=5)

只是坐着看命令提示符什么也不做(它似乎被困在 winspawn 方法中)。我想知道还有什么其他方法可以编写 Python 脚本以与命令行交互以达到与我在 Unix 中能够达到的效果相同的效果?如果合适的 Windows 版本 pexpect 脚本不存在,我可以使用什么其他方法来解决这个问题?

最佳答案

您可以使用 wexpect (“预期的 Windows 替代方案”,Python 软件基金会)。它具有相同的功能,并且可以在 Windows 上运行。

关于python - Windows 替代预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38976893/

相关文章:

php - 使用 CLI 来使用 phar 文件不起作用

angular - 如何在没有 cli 的情况下构建 angular 2 应用程序

python - UnboundLocalError : local variable 'sum' referenced before assignment

python - QLineEdit 更改边框颜色而不更改边框样式

python - NoBrokersAvailable : NoBrokersAvailable Error in Kafka

linux - 在本地 Windows 计算机中运行 postgres 命令时出现问题。在Linux、Mac下运行成功,但在windows下失败

postgresql - Postgres 命令行 - 清除/删除我正在输入的查询

Python Spyder 初始化 Hello World Kivi 应用程序一次?

c# - 如何枚举所有可用的无线网络并将它们显示在列表框中?

c++ - Qt 手势。没有收到 qgesture 事件