我想使用 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
您能建议如何解决这个问题吗?
谢谢。
最佳答案
Pywinrm 使用域用户帐户连接:
在远程 Windows 机器中
- 确保目标 Windows 机器的网络连接类型是“私有(private)”,如果是“公共(public)”,则不会配置 winrm。
打开命令提示符并输入:
winrm qc winrm set winrm/config/service @{AllowUnencrypted="true"}
打开 Powershell 并输入:
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
关于python - 如何使用域帐户通过 Python (pywinrm) 中的 WinRM 连接到远程计算机?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32324023/