0

这是Python 脚本未执行 sysinternals 命令的后续

我的脚本需要输入

python ps.py sender-ip=10.10.10.10

sender-ip 被读入变量 userIP。但是,当我将 userIP 传递到以下子进程时

pst = subprocess.Popen(
        ["D:\pstools\psloggedon.exe", "-l", "-x", "\\\\", userIP],
        stdout = subprocess.PIPE,
        stderr = subprocess.PIPE
    )

out, error = pst.communicate()

userLoggedOn = out.split('\n')[1].strip()
print 'userId={}'.format(userloggedon)

脚本将输出

userId=

如何让子进程读取用户 IP 以便执行

D:\pstools\psloggedon.exe  -l -x \\userIP

并输出

userId=DOMAIN\user

编辑

执行脚本的命令行是

python py.ps sender-ip=10.10.10.10

当我手动执行

D:\PSTools\PsLoggedon.exe -l -x \\10.10.10.10

我得到了我正在寻找的结果

4

3 回答 3

1

您的麻烦在于可执行文件的名称。单个反斜杠就像转义字符一样工作,因此如果您要打印要启动的命令的名称,您会看到反斜杠丢失了。

选项包括:

cmd = r"D:\pstools\psloggedon.exe" # raw string prefix r
print cmd
cmd = "D:\\pstools\\psloggedon.exe" # double backslash
print cmd
cmd = "D:/pstools/psloggedon.exe" # forward slash works also on windows
print cmd

您可以尝试使用以下成语,这样可以更好地检测问题

userIP="\\\\"+userIP

cmd = ["D:\\pstools\\psloggedon.exe"]
cmd.extend(["-l", "-x", userIP])
print "cmd", cmd # do it only, if you are developing
pst = subprocess.Popen(
        cmd,
        stdout = subprocess.PIPE,
        stderr = subprocess.PIPE
    )

这使您可以打印出来cmd并查看是否存在可见的问题。

注意:上面的代码建立在公认的答案解决方案上(它添加了正确的解决方案,userIP但可能存在反斜杠问题)。

于 2014-05-15T19:45:34.783 回答
1

'\\\\'并且userIP不是单独的选项,但您将其传递给 psloggedon.exe 就好像它们是分开的。

将它们粘成一根绳子:

userIP="\\\\"+userIP
pst = subprocess.Popen(
        ["D:\pstools\psloggedon.exe", "-l", "-x",  userIP],
        stdout = subprocess.PIPE,
        stderr = subprocess.PIPE
    )

还请查看您的打印声明。您设置userLoggedOn变量,然后使用userloggedon.

于 2014-05-15T19:48:32.020 回答
1

使其工作的最简单方法是使用原始字符串文字以避免在字符串文字中转义反斜杠,并在 Windows 上将命令作为字符串传递:

from subprocess import check_output

output = check_output(r"D:\pstools\psloggedon.exe  -l -x \\userIP")
print(output.splitlines())
于 2014-05-16T05:30:57.920 回答