Windows替代pexp

2024-06-08 08:28:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个跨平台的工具,它运行特定的命令,需要特定的验证输出,并发送特定的验证输出(如用户名/密码)。

在Unix上,我成功地编写了一个使用pexpect库(通过pip install pexpect)的Python工具。这段代码工作得很好,正是我要做的。我提供了我的代码的一小部分,以证明以下概念:

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'

根据pexpectdocumentation

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,甚至更新的(分叉的)版本here,但这两个项目似乎都不起作用。我使用的方法是:

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

只是坐在那里看着命令提示符什么也不做(它似乎被困在winspawn方法中)。我想知道还有什么其他方法可以让我编写一个Python脚本来与命令行交互,从而达到与在Unix中一样的效果呢?如果一个合适的工作Windows版本pexpect脚本不存在,我可以使用什么其他方法来实现这一点?


Tags: toselfserverwindowsasmatchnotsw
2条回答

您可以使用windows来代替pexpect.spawn

child = pexpect.popen_spawn.PopenSpawn('cmd', timeout=1)
child.send('ipconfig')
child.expect('Wireless', timeout=None)

您可以使用wexpect(“pexpect的Windows替代品”,Python软件基础)。它具有相同的功能,并且可以在Windows上运行。

相关问题 更多 >