在Windows机器上执行命令的子进程

时间:2017-08-22 19:22:30

标签: python subprocess wmi pywin32

我正在尝试连接到远程Windows机器,并从命令行执行一些命令。命令如下:我在某个文件夹中有可执行文件,转到该文件夹​​并运行命令

InstallUtil.exe <exe_name>

这是我的代码:

  class WindowsMachine:
def __init__(self, hostname, username, password):
    self.hostname = hostname
    self.username = username
    self.password = password
    # self.remote_path = hostname
    try:
        print("Establishing connection to .....%s" %self.hostname)
        connection = wmi.WMI(self.hostname, user=self.username, password=self.password)
        print("Connection established")

        try:

            print(os.listdir(r"C:\Program Files\BISYS\BCE"))

            a = subprocess.check_output(["InstallUtil.exe","IamHere.exe"], cwd="C:/Program Files/ABC/BCD/",stderr=subprocess.STDOUT)
            print(a)


        except subprocess.CalledProcessError as e:
            raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))


    except wmi.x_wmi:
        print("Could not connect to machine")
        raise

w = WindowsMachine(hostname,username,password)
print(w)
print(w.run_remote())

但我收到错误说:

WindowsError: [Error 2] The system cannot find the file specified

1 个答案:

答案 0 :(得分:0)

如评论中所述,如果您的目标是首先在远程Windows机器上运行进程,则应该保持远程连接处于打开状态,因此不要将其存储在本地变量connection中,而是将其存储在类成员中self.connection。 现在,要使用WMI在远程计算机上执行命令,您应该执行this(WMI tutorial)

之类的操作
class ConnectToRemoteWindowsMachine:
      def __init__(self, hostname, username, password):
          self.hostname = hostname
          self.username = username
          self.password = password
          # self.remote_path = hostname
          try:
              print("Establishing connection to .....%s" %self.hostname)
              self.connection = wmi.WMI(self.hostname, user=self.username, password=self.password)
              print("Connection established")
          except wmi.x_wmi:
              print("Could not connect to machine")
              raise

      def run_remote(self, async=False, minimized=True):

          SW_SHOWNORMAL = 1

          process_startup = self.connection.Win32_ProcessStartup.new()
          process_startup.ShowWindow = SW_SHOWNORMAL

          process_id, result = c.Win32_Process.Create(
              CommandLine="notepad.exe",
              ProcessStartupInformation=process_startup
          )
          if result == 0:
              print "Process started successfully: %d" % process_id
          else:
              raise RuntimeError, "Problem creating process: %d" % result


w = ConnectToRemoteWindowsMachine(hostname,username,password)
print(w)
print(w.run_remote())