远程执行Powershell命令并使用wmi python打印输出

时间:2018-07-26 17:36:16

标签: python wmi

我想远程执行powershell命令并获取输出。 该命令是“((New-Object -c Microsoft.Update.Session).CreateUpdateSearcher()。Search(“ IsInstalled = 0”)。Updates | Select Title“。
我尝试过

import wmi
try:
  connection = wmi.WMI(ip, user=username, password=password)
  print("connection is established")
  connection.Win32_Process.Create(CommandLine='powershell.exe /c (New-Object -c Microsoft.Update.Session).CreateUpdateSearcher().Search("IsInstalled=0").Updates|Select Title  > C:\output.txt')
except:
  print("connection failed")

1 个答案:

答案 0 :(得分:0)

您需要照顾转义字符。试试这个:

import wmi
try:
  connection = wmi.WMI(ip, user=username, password=password)
  print("connection is established")
  connection.Win32_Process.Create (CommandLine=" powershell.exe -command \" & {New-Object -c Microsoft.Update.Session).CreateUpdateSearcher(). Search(\"IsInstalled=0\").Updates|Select Title}\"  > C:\output.txt")
except:
  print("connection failed")