How to connect to remote machine via WinRM in Python (pywinrm) using domain account?

Stanislav Hordiyenko picture Stanislav Hordiyenko · Sep 1, 2015 · Viewed 32.6k times · Source

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.

Answer

SirDisney picture SirDisney · Sep 18, 2015

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.