使用find与psexec发布问题

时间:2015-08-07 15:01:29

标签: python python-2.7 cmd find psexec

我遇到了一个问题,即获取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机器上远程执行命令的东西,因为我试图计算字符串的文件非常大,并且会返回几个结果万。

1 个答案:

答案 0 :(得分:0)

我找到了一个解决方法!我仍在使用find,但现在不是直接使用它,而是将findstr的结果用于管道。

以下是cmd_line现在的样子:

cmd_line = r'psexec \\{0} cmd /c "findstr /c:"{1}" "{2}" | find /v /c """'.format(address, findstr, file)