如何用Python从Ubuntu远程执行本地Batch/Powershell脚本到Windows并获取结果?
解决Ubuntu远程执行本地Batch/PowerShell脚本到Windows的方案
刚好我之前处理过类似的需求,给你两个实用的方案,直接解决你的痛点——不用把脚本提前放到Windows机器上,从Ubuntu用Python远程执行本地的Batch/PowerShell脚本还能拿结果:
方案一:使用pywinrm(推荐,原生适配Windows远程管理)
pywinrm是专门用于和Windows远程管理(WinRM)服务交互的Python库,不需要在Windows上额外装SSH服务,配置更简单。
步骤1:安装pywinrm
在Ubuntu上执行:
pip install pywinrm
步骤2:配置远程Windows机器
以管理员身份在Windows上打开PowerShell,执行以下命令开启WinRM服务并允许远程连接:
winrm quickconfig如果你的Ubuntu机器不在Windows的域环境里,还需要添加信任主机(把
your-ubuntu-ip换成你的Ubuntu机器IP):winrm set winrm/config/client '@{TrustedHosts="your-ubuntu-ip"}'
步骤3:Python代码示例
执行本地PowerShell脚本
import winrm # 初始化WinRM会话 winrm_session = winrm.Session( "your-windows-ip-or-hostname", auth=("windows-username", "windows-password"), transport="ntlm" # 大部分Windows环境用ntlm认证即可 ) # 读取本地PowerShell脚本内容 with open("local_script.ps1", "r", encoding="utf-8") as f: ps_script_content = f.read() # 执行脚本并获取结果 result = winrm_session.run_ps(ps_script_content) # 处理输出 print("执行返回码:", result.status_code) print("标准输出:\n", result.std_out.decode("utf-8")) print("错误输出:\n", result.std_err.decode("utf-8"))
执行本地Batch脚本
Batch脚本通常用GBK编码,注意编码适配:
import winrm winrm_session = winrm.Session( "your-windows-ip-or-hostname", auth=("windows-username", "windows-password"), transport="ntlm" ) # 读取本地Batch脚本内容 with open("local_script.bat", "r", encoding="gbk") as f: bat_script_content = f.read() # 通过cmd /c执行Batch脚本 cmd_command = f'cmd /c "{bat_script_content}"' result = winrm_session.run_cmd(cmd_command) # 输出结果(用GBK解码) print("执行返回码:", result.status_code) print("标准输出:\n", result.std_out.decode("gbk")) print("错误输出:\n", result.std_err.decode("gbk"))
方案二:结合paramiko+OpenSSH Server(适合习惯paramiko的场景)
如果坚持想用paramiko,需要先在Windows上安装OpenSSH Server,然后通过SFTP上传脚本到远程,再执行。
步骤1:在Windows上安装OpenSSH Server
以管理员身份打开PowerShell,执行:
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
安装完成后启动服务:
Start-Service sshd Set-Service -Name sshd -StartupType 'Automatic'
步骤2:Python代码示例
import paramiko # 建立SSH连接 ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect( hostname="your-windows-ip", username="windows-username", password="windows-password" ) # 上传本地脚本到Windows临时目录 local_script_path = "local_script.ps1" remote_script_path = "C:\\Temp\\remote_script.ps1" # 确保Temp目录存在 with ssh_client.open_sftp() as sftp: sftp.put(local_script_path, remote_script_path) # 执行远程脚本(绕过执行策略限制) stdin, stdout, stderr = ssh_client.exec_command( f'powershell -ExecutionPolicy Bypass -File "{remote_script_path}"' ) # 获取执行结果 print("标准输出:\n", stdout.read().decode("utf-8")) print("错误输出:\n", stderr.read().decode("utf-8")) # 关闭连接 ssh_client.close()
如果是Batch脚本,把执行命令换成:
stdin, stdout, stderr = ssh_client.exec_command(f'cmd /c "{remote_script_path}"')
内容的提问来源于stack exchange,提问作者shanks
相关产品推荐
相关产品推荐

