I would like to write a script in Python using pywinrm library to be able to connect to remote machine via 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
Script is working fine when I use local user. When I use domain user, I receive the following exception:
winrm.exceptions.UnauthorizedError: 401 Unauthorized.
As to the WinRM configuration on remote machine:
/Client/Auth/Basic = True
/Client/TrustedHosts = *
/Service/Auth/Basic = True
/Service/AllowUnencrypted = True
Could you advise how to fix this issue?
Thank you.
WinRM establishes a session with a remote computer through the SOAP-based WS-Management protocol rather than a connection through DCOM, as WMI does. Data returned to WS-Management protocol are formatted in XML rather than in objects.
It allows you to invoke commands on target Windows machines from any machine that can run Python. WinRM allows you to perform various management tasks remotely. These include, but are not limited to: running batch scripts, powershell scripts, and fetching WMI variables.
Open command prompt and type:
winrm qc
winrm set winrm/config/service @{AllowUnencrypted="true"}
Open Powershell and type:
enable-psremoting
set-item WSMan:\localhost\Client\TrustedHosts * # ('*' is for all hosts, you may specify the host you want)
In your python script:
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
As Steve Barnes said, you user should kerberos to connect using your domain account.
You will first need a kerberos ticket set up for your account. Windows will give this to you automatically, but under linux you will need to kinit. Use klist to see your current and default tickets.
session = winrm.Session(server, auth=('user@DOMAIN', 'doesNotMatterBecauseYouAreUsingAKerbTicket'), transport='kerberos')
I believe your domain account needs to have admin permissions on the windows host.
Also note that in version 0.0.3 of pywinrm you can specify the auth param as:
auth=(None, None)
This is because pywinrm is using your default kerberos ticket.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With