在Windows machin上执行命令的子进程

2024-06-11 10:54:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图连接到远程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())

但我错了说:

^{pr2}$

Tags: 命令self文件夹remoteusernamepasswordconnectionwmi
1条回答
网友
1楼 · 发布于 2024-06-11 10:54:21

如注释中所述,如果您的目标是首先在远程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())

相关问题 更多 >