使用Python重启WinRM时subprocess返回非零退出状态1如何解决
解决方案
故障根因
- 代码中使用了中文全角引号
“”,PowerShell仅支持识别半角英文引号 - 调用PowerShell时未显式指定
-Command参数,命令解析逻辑易出现异常 - 未使用列表形式传递命令参数,存在特殊字符转义风险
- 运行Python的终端没有管理员权限,修改系统服务状态默认需要高权限
subprocess.check_output默认不捕获错误输出,无法定位具体报错(比如权限不足、服务不存在等)
可用实现代码
方案1:列表传参(推荐,无需处理转义)
import subprocess # 运行前请确保以管理员身份启动Python终端 try: # 如需启动服务则将Restart-Service改为Start-Service output = subprocess.check_output( ["powershell.exe", "-Command", "Restart-Service", "-Name", "WinRM"], stderr=subprocess.STDOUT, text=True ) print("执行成功,输出:", output) except subprocess.CalledProcessError as e: print("执行失败,错误信息:", e.output)
方案2:字符串形式(全用半角符号)
import subprocess try: output = subprocess.check_output( 'powershell.exe -Command "Restart-Service -Name WinRM"', stderr=subprocess.STDOUT, text=True ) print("执行成功,输出:", output) except subprocess.CalledProcessError as e: print("执行失败,错误信息:", e.output)
验证方法
- 右键点击终端(命令提示符/PowerShell/Windows终端),选择「以管理员身份运行」
- 在管理员终端中启动Python,运行上述代码
- 执行
powershell.exe Get-Service WinRM可手动确认WinRM服务状态
内容的提问来源于stack exchange,提问作者irom
相关产品推荐
相关产品推荐

