WinRM是在Windows服务器远程连接另一台Windows服务器执行命令或PowerShell cmdlet的协议。在Linux服务器上安装WinRM客户端之后可使用WinRM协议操作Windows服务器,pywinrm是Python里的WinRM客户端模块。

介绍Windows服务器上设定WinRM服务及Linux上安装pywinrm的方法,而访问Windows服务器时认证方法采用Basic认证

Windows服务器上启用WinRM

远程连接Windows服务器之后,以管理员身份启动命令行。

在命令行上运行 winrm quickconfig

执行 winrm enumerate winrm/config/listener 命令确认结果。

设定为Basic认证。

C:\> winrm set winrm/config/service @{AllowUnencrypted="true"}
C:\> winrm set winrm/config/service/auth @{Basic="true"}

执行 winrm get winrm/config 命令确认结果。

最后在Windows的服务一览上确认WinRM(Windows Remote Management)服务在Running的状态。

Linux上安装pywinrm

使用pip3命令安装pywinrm模块。

# pip3 install pywinrm

如果安装pywinrm时出现如下错误的话,添加 –trusted-host pypi.python.org选项后,执行pip3 install pywinrm –trusted-host pypi.python.org
命令。

Collecting pywinrm
  Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:897)'),)': /simple/pywinrm/
  Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:897)'),)': /simple/pywinrm/
  Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:897)'),)': /simple/pywinrm/
  Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:897)'),)': /simple/pywinrm/
  Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:897)'),)': /simple/pywinrm/
  Could not fetch URL https://pypi.python.org/simple/pywinrm/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.python.org', port=443): Max retries exceeded with url: /simple/pywinrm/ (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:897)'),)) - skipping
  Could not find a version that satisfies the requirement pywinrm (from versions: )
No matching distribution found for pywinrm

远程执行命令(Linux->Windows)

启动python3之后导入winrm模块,并在session设定Windows服务器的连接信息后执行Get-Date命令。

# python3
>>> import winrm
>>> session = winrm.Session('<Windows服务器IP地址>', auth=('<用户名>','<密码>'))
>>> session.run_ps("Get-Date").std_out

如下显示时间的话,表示从Linux远程执行Windows命令成功。

b'\r\nFriday, September 23, 2022 7:01:16 AM\r\n\r\n\r\n'

介绍了在Linux上使用Python的pywinrm模块远程连接Windows服务器执行PowerShell或者CMD命令的方法。