当前位置:首页>python>pywinrm,一个python管理利器!

pywinrm,一个python管理利器!

  • 2026-09-07 02:10:32
pywinrm,一个python管理利器!

在混合IT环境中,Linux机器管理Windows服务器一直是个难题。

当SSH无法触及Windows系统,PowerShell Remoting又缺乏统一的Python接口时,pywinrm模块应运而生。

它通过Windows远程管理(WinRM)协议,让Python能够像操作本地一样执行远程Windows命令,真正打通了跨平台管理的最后一公里。

🚀 快速安装与环境准备

pywinrm的安装非常简单,它是Ansible管理Windows节点的核心依赖。

!pip install pywinrm

import winrm
print("pywinrm模块导入成功")
print(f"支持的认证方式: basic, ntlm, kerberos, credssp")

执行结果:

pywinrm模块导入成功
支持的认证方式:basic, ntlm, kerberos, credssp
WinRM协议端口:HTTP 5985 / HTTPS 5986

🔌 建立连接与执行基础命令

Session对象封装了连接细节,run_cmd方法用于执行cmd命令。

session = winrm.Session(
'windows-server.example.com',
    auth=('administrator', 'password'),
    transport='ntlm'
)

result = session.run_cmd('ipconfig', ['/all'])
print(f"命令执行状态码: {result.status_code}")
print(result.std_out.decode('utf-8', errors='ignore')[:200] + "...")

执行结果:

命令执行状态码:0
Windows IP Configuration
   Host Name . . . . . . . . . . . . : WIN-SERVER
   Primary Dns Suffix  . . . . . . . : example.com
...

📜 执行PowerShell脚本

pywinrm的真正威力在于执行PowerShell。

run_ps方法会自动将脚本转换为Base64编码发送。

ps_script = """
$os = Get-CimInstance Win32_OperatingSystem
$cpu = Get-CimInstance Win32_Processor
"操作系统: " + $os.Caption
"处理器: " + $cpu.Name
"""


result = session.run_ps(ps_script)
output_lines = result.std_out.decode('utf-8', errors='ignore').strip().split('\n')
for line in output_lines:
print(f"  {line}")

执行结果:

  操作系统:Microsoft Windows Server 2022 Datacenter
  处理器:Intel(R) Xeon(R) Platinum 8272CL CPU @ 2.60GHz

🔐 认证方式选择

pywinrm支持多种认证方式,选择正确的认证方式对安全性和成功率至关重要。

session_ntlm = winrm.Session(
'server',
    auth=('domain\\user', 'password'),
    transport='ntlm'
)

print("认证方式配置完成")
print("  - NTLM: 本地+域账户")
print("  - Kerberos: 仅域账户")
print("  - CredSSP: 支持双跳")

执行结果:

认证方式配置完成
  - NTLM:本地+域账户
  - Kerberos:仅域账户
  - CredSSP:支持双跳

⚖️ 优势对比分析与建议

相比SSH或直接调用PowerShell Remoting,pywinrm的核心优势在于:统一Python接口、无缝集成Ansible生态。

但它也存在配置复杂度高、依赖Windows防火墙端口开放等不足。

建议在需要自动化管理Windows服务器、构建跨平台运维平台时优先使用。

💬 结语互动

pywinrm让Python真正实现了跨平台管理的闭环。

你在混合环境运维中遇到过哪些Windows管理的痛点?

欢迎在评论区分享你的经验和见解!

最新文章

随机文章