如何使用域帐户通过Python中的WinRM(pywinrm)连接到远程计算机?

如何使用域帐户通过Python中的WinRM(pywinrm)连接到远程计算机?,python,winrm,Python,Winrm,我想使用pywinrm库编写Python脚本,以便能够通过WinRM连接到远程机器 import winrm s = winrm.Session('MACHINEHOST', auth=('username@domain', 'password')) r = s.run_cmd('ipconfig', ['/all']) print r.status_code print r.std_out 当我使用本地用户时,脚本工作正常。当我使用域用户时,我收到以下异常: winrm.exceptio

我想使用pywinrm库编写Python脚本,以便能够通过WinRM连接到远程机器

import winrm

s = winrm.Session('MACHINEHOST', auth=('username@domain', 'password'))
r = s.run_cmd('ipconfig', ['/all'])

print r.status_code
print r.std_out
当我使用本地用户时,脚本工作正常。当我使用域用户时,我收到以下异常:

winrm.exceptions.UnauthorizedError: 401 Unauthorized.
关于远程计算机上的WinRM配置:

/Client/Auth/Basic = True
/Client/TrustedHosts = *
/Service/Auth/Basic = True
/Service/AllowUnencrypted = True
你能建议如何解决这个问题吗


谢谢。

正如Steve Barnes所说,您的用户应该使用您的域帐户连接kerberos

您首先需要为您的帐户设置kerberos票证。Windows会自动将其提供给您,但在linux下,您需要将其kinit。使用klist查看当前和默认票据

session = winrm.Session(server, auth=('user@DOMAIN', 'doesNotMatterBecauseYouAreUsingAKerbTicket'), transport='kerberos')
我相信您的域帐户需要在windows主机上具有管理员权限

还请注意,在pywinrm的0.0.3版中,可以将auth参数指定为:

auth=(None, None)

这是因为pywinrm正在使用默认的kerberos票证。

使用此powershell脚本启用winrm并将winrm配置到所有windows节点

要使用域用户帐户连接的Pywinrm: 在远程Windows计算机中
  • 确保目标windows计算机中的网络连接类型为“专用”,如果为“公用”,则不会配置winrm
  • 打开命令提示符并键入:

    winrm qc
    winrm set winrm/config/service @{AllowUnencrypted="true"}
    
    enable-psremoting
    set-item WSMan:\localhost\Client\TrustedHosts * # ('*' is for all hosts, you may specify the host you want)
    
  • 打开Powershell并键入:

    winrm qc
    winrm set winrm/config/service @{AllowUnencrypted="true"}
    
    enable-psremoting
    set-item WSMan:\localhost\Client\TrustedHosts * # ('*' is for all hosts, you may specify the host you want)
    
  • 在Python代码中
  • 在python脚本中:

    import winrm
    
    host = 'YourWindowsHost'
    domain = 'YourDomain'
    user = 'YourDomainUser'
    password = 'YourPassword'
    
    session = winrm.Session(host, auth=('{}@{}'.format(user,domain), password), transport='ntlm')
    
    result = session.run_cmd('ipconfig', ['/all']) # To run command in cmd
    
    result = session.run_ps('Get-Acl') # To run Powershell block
    

  • 建议对域上的远程主机使用Kerberos。