使用Python调用PsExec时参数语法异常,执行后返回帮助信息而非预期结果
使用Python调用PsExec时参数语法异常,执行后返回帮助信息而非预期结果
我完全懂你这种头疼的情况——手动在CMD里敲PsExec命令明明能正常输出"hello world",但用Python的subprocess调用就直接返回帮助文档,肯定是参数传递的方式出问题了。
咱们先拆解下你代码里的核心问题:你给PsExec的路径后面加了多余空格,还把所有参数拼成一个字符串塞进列表里,再配合shell=True的用法,导致PsExec根本没收到正确的参数,自然就输出帮助信息提示你语法不对了。
这里给你两种经过验证的修正方案:
方案一:推荐用法——拆分参数为列表(不使用shell=True)
这种方式是subprocess官方推荐的,能避免大部分因空格、引号导致的参数解析错误:
import subprocess myusername = 'DOMAIN\\myusername123' mypassword = 'mypassword123' remote_command = 'echo Hello, World!' # 把每个参数拆成列表的独立元素,注意路径不要加多余空格 command_args = [ 'c:\\pstools\\psexec.exe', '-s', '-u', myusername, '-p', mypassword, '-accepteula', 'cmd.exe', '/c', remote_command ] # 同时捕获stdout和stderr,方便调试错误 process = subprocess.Popen(command_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output, _ = process.communicate() # 解码输出并打印 output_str = output.decode('utf-8') print(f'Output:\n{output_str}')
方案二:使用shell=True(拼成完整命令字符串)
如果你一定要用shell=True,那就要把整个命令拼成一个完整的字符串,而不是用列表传递:
import subprocess myusername = 'DOMAIN\\myusername123' mypassword = 'mypassword123' remote_command = 'echo Hello, World!' # 拼接成完整的命令字符串,路径后不要加空格 full_command = f'c:\\pstools\\psexec.exe -s -u {myusername} -p {mypassword} -accepteula cmd.exe /c {remote_command}' process = subprocess.Popen(full_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) output, _ = process.communicate() output_str = output.decode('utf-8') print(f'Output:\n{output_str}')
原代码出错的关键原因
- 路径后的多余空格:你写的
'c:\\pstools\\psexec.exe '(末尾有空格)会被系统当成带空格的文件路径,导致无法正确找到PsExec程序; - 参数传递方式错误:当使用
shell=True时,如果你传递列表参数,第一个元素是shell的命令(比如cmd.exe),后面的元素是shell的参数,而不是PsExec的参数,这就导致PsExec没有接收到你指定的-s、-u等参数,所以返回帮助文档。
备注:内容来源于stack exchange,提问作者CrossingTheRoad2020
相关产品推荐
相关产品推荐

