从Python脚本调用psexec时未显示完整输出

1 投票
1 回答
3980 浏览
提问于 2025-04-18 16:57

我想用一个Python脚本来显示我们域里的所有本地管理员。

我的代码:

for line in open(anfangsrechner,"r"):

    zeile = line.strip()

    command ='\\\\' +zeile+ ' -i' ' net' ' localgroup' ' Administratoren'

    abfrage = subprocess.Popen(['PsExec.exe ',command,],stdin=subprocess.PIPE,
                               stdout=subprocess.PIPE, )
    # print (abfrage)

    while True:
        line = abfrage.communicate()
        if not line:
            break
        print (line)

但是我从psexec命令中只得到了这个:

PsExec v2.1 - Execute processes remotely Copyright (C) 2001-2013 Mark
Russinovich Sysinternals - www.sysinternals.com


Process finished with exit code 0

我没有得到完整的输出。有没有人知道我该怎么解决这个问题?

1 个回答

1

你现在传递的参数是一个长字符串,而不是一个列表。

一个简单的解决办法是使用 shell=True

abfrage = subprocess.Popen('PsExec.exe '+command, 
                           stdout=subprocess.PIPE, 
                           shell=True)

正确的做法是创建一个参数列表,然后传递这个列表。

引用一下文档中的内容:

在所有调用中,args是必需的,它应该是一个字符串,或者是一系列程序参数。一般来说,提供参数序列是更好的选择,因为这样可以让模块处理任何必要的转义和引号问题(例如,允许文件名中有空格)。如果传递一个单独的字符串,要么必须将shell设置为True(见下文),要么这个字符串只能是要执行的程序名称,而不指定任何参数。

撰写回答