在Python子进程中解析变量

0 投票
3 回答
825 浏览
提问于 2025-04-18 06:42

这是接着之前一个问题的内容,链接在这里:Python脚本没有执行sysinternals命令

我的脚本需要输入

python ps.py sender-ip=10.10.10.10

发送者的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=

我该如何让这个子进程读取userIP,以便它能执行

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

我得到了我想要的结果

3 个回答

1

让它正常工作的最简单方法是使用原始字符串字面量,这样就可以避免在字符串中需要转义反斜杠,并且在Windows上将命令作为字符串传递:

from subprocess import check_output

output = check_output(r"D:\pstools\psloggedon.exe  -l -x \\userIP")
print(output.splitlines())
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 提供了解决方案,但可能在反斜杠方面会有问题)。

1

'\\\\'userIP 其实不是两个不同的选项,而是你在使用 psloggedon.exe 的时候,把它们当成了两个选项来传递。

把它们合并成一个字符串:

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

还有,看看你的打印语句。你设置了 userLoggedOn 这个变量,但在打印的时候却用的是 userloggedon

撰写回答