我遇到了一个问题,即获取psexec并找到在我的python函数中很好地一起玩。这是我试图开始工作的功能:
def CountString(address, file, findstr):
cmd_line = r'psexec \\{0} cmd /c find /c "{1}" "{2}"'.format(address, findstr, file)
print cmd_line
myP = subprocess.Popen(cmd_line, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
out = timeout(myP.communicate, (), {}, 30, (None, None))
return out
以下是我如何测试该功能的示例:
test = CountString(r'RemotePC', r'c:\directory\File to Count.txt', r'String to count')
print test
在我的第一段代码中,我添加了print cmd_line
以验证cmd行看起来是否正确,以及我可以告诉它的内容。如果我使用我的示例输入运行该函数,则返回:
psexec \\RemotePC cmd /c find /c "String to count" "c:\directory\File to Count.txt"
我甚至可以将print cmd_line
的输出复制并粘贴到cmd窗口中,然后按预期工作:
C:\>psexec \\RemotePC cmd /c find /c "String to count" "c:\directory\File to Count.txt"
PsExec v1.97 - Execute processes remotely
Copyright (C) 2001-2009 Mark Russinovich
Sysinternals - www.sysinternals.com
---------- c:\directory\File to Count.txt: 3600
cmd exited on RemotePC with error code 0.
C:\>
但由于某种原因,我无法让python函数返回结果,它只会坐在那里并挂起,如果我没有超时。
我还尝试更改cmd_line
的语法,在""
周围添加find /c "{1}" "{2}"
:
cmd_line = r'psexec \\{0} cmd /c "find /c "{1}" "{2}""'.format(address, findstr, file)
print cmd_line
的输出再次来自cmd行本身,但不会在python中一致地工作。
我注意到的一个奇怪的事情是,这将返回我想要的25次尝试中的1次。但是,当我再次针对相同的远程PC和同一文件运行它时,它会失败。
注意:我不反对使用除find
之外的其他内容,如果还有其他内容会返回我想在文件中找到的字符串数。但我确实需要使用psexec
,或允许我在XP机器上远程执行命令的东西,因为我试图计算字符串的文件非常大,并且会返回几个结果万。
答案 0 :(得分:0)
我找到了一个解决方法!我仍在使用find
,但现在不是直接使用它,而是将findstr
的结果用于管道。
以下是cmd_line
现在的样子:
cmd_line = r'psexec \\{0} cmd /c "findstr /c:"{1}" "{2}" | find /v /c """'.format(address, findstr, file)