【问题标题】:cannot run powershell script with pywinrm无法使用 pywinrm 运行 powershell 脚本
【发布时间】:2017-05-26 06:20:55
【问题描述】:

这里我们可以看到一些例子: https://github.com/diyan/pywinrm 如何通过pywinrm和powershell脚本控制windows 这是工作。

万一

ps_script = """$strComputer = $Host
[Environment]::SetEnvironmentVariable("Path", $env:Path + ";C:\Python27\Scripts", [EnvironmentVariableTarget]::Machine)
Restart-Computer 
"""

它将 python 添加到 PATH,但不重新启动 Windows。

万一

ps_script = """Write-Host "hello"
    """

我在我的机器终端上看到“你好”,而不是远程。

怎么了?

【问题讨论】:

  • 几个想法。您尝试重新启动哪个版本的 Windows?使用什么版本的 PowerShell?如果我没记错的话,直到 PowerShell 3.0 才添加 Restart-Computer。其次,如果添加-force 参数会发生什么?
  • @BenH, "restart-computer -force" 成功。但是什么权利? Windows server 2012, powershell 3.0 我的用户已经在管理组中。
  • 实际上,Retart-Computer -Force AFAIR 只是忽略了远程机器上有活动的会话这一事实。没有它,如果存在任何会话,PowerShell 将返回错误。检查您从 response 获得的 std_err 对象(只是猜测,因为您跳过了代码的那部分)run_ps 方法。

标签: powershell python-2.x winrm


【解决方案1】:

pywinrm 的工作方式是:

  • 以类似于 Windows 上的winrs 命令的方式连接到 WinRM
  • 当您决定运行 PowerShell 脚本时 - 它会转换为 powershell.exe -encodedCommand 可接受的格式(请参阅 pywinrm code 中调用 PowerShell 的行)
  • 结果被传回python,这样你就可以print它,或者做任何你需要的事情

不确定您对Write-Host 的期望是什么 - 它只是一个写入托管 PowerShell 的应用程序的 cmdlet(如果是 pywinrm - 那将是 PowerShell.exe)并且主机负责处理它 - 在你的情况,写到std_out。所以我猜它到达你的控制台也就不足为奇了。

关于重新启动计算机 - 当有活动用户时,它往往会出错。该消息将在 pywinrm 代码的 std_err 中结束 - 您可能需要分析 return_code 并根据值进行响应:

session = Session(...)
result =  session.run_ps(command)
print result.std_out
if result.status_code != 0:
    print "Error: %s" % result.std_err

我怀疑你没有对 std_err 做任何事情,所以 PowerShell 向你抛出的任何错误都保持沉默。

【讨论】:

  • 我试试这个r = s.run_ps(ps_script) print(r.std_err),终端没有声音
猜你喜欢
  • 2020-12-05
  • 1970-01-01
  • 2021-05-13
  • 2017-09-22
  • 2023-04-01
  • 2016-07-13
  • 2013-01-02
  • 2018-03-21
  • 2016-09-14
相关资源
最近更新 更多