我正在尝试自动执行用 C++ 编写的交互式命令行工具。
启动时,二进制文件等待字母 S、Q 或 P(状态、退出或暂停)。它使用非标准 msvcrt 函数“getche”来获取击键(而不是例如 gets()),而无需用户按 Enter 键。
我尝试以标准方式与进程通信(写入 stdin 并使用 process.communicate[]),但它没有获取输入。经过几个小时的尝试不同的事情后,我在 Visual Studio 中创建了两个小示例项目来复制该问题并确保我头脑清醒。
这是用于调用二进制文件的 python 脚本:
import subprocess
import time
cmd = ["test-getch.exe"]
process = subprocess.Popen(cmd, stderr = subprocess.PIPE, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
i = process.stdin
#msvcrt.ungetch('s')
i.write("S\n")
print process.communicate()[0]
i.close()
time.sleep(3)
print "DONE"
这是两个二进制文件。我可以与之交流的第一个:
#include "stdafx.h"
#include <conio.h>
int _tmain(int argc, _TCHAR* argv[])
{
char response [2];
printf("Enter \"s\":\n");
gets(response);
printf("You entered %s", response);
return 0;
}
我无法与之沟通的人:
#include "stdafx.h"
#include <conio.h>
int _tmain(int argc, _TCHAR* argv[])
{
int response;
printf("Enter \"a\":\n");
response = getche();
printf("You entered %c", response);
return 0;
}
看来 getche() 不监听标准输入,并且可能监听某种键盘事件。有人知道如何处理这个问题吗?
EDIT:我还应该提到我发现了使用 IDA Pro 捕获输入的方法。我没有编写我试图自动化的原始二进制文件。它是一个闭源工具,因此我无法在不修补二进制文件的情况下重写它接受输入的方式。
我实际上选择了一个相当疯狂的有效解决方案...我非常了解 pydbg,并且似乎通过流程仪表附加到流程并调用我需要的函数是可行的。这完全是多余的,但之后我可以脱离这个过程。并让它正常运行。
[1]Pydbg:http://pedram.redhive.com/PyDbg/docs/