Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/env python
from ctypes import windll, c_wchar_p, c_ulong, c_void_p, pointer
from ctypes.wintypes import HANDLE
class WindowsAuthentication(object):
class Logon32:
LOGON32_LOGON_NETWORK = 3
LOGON32_PROVIDER_DEFAULT = 0
def __init__(self, username, domain, debug=False):
self.token = HANDLE(0)
self.username = username
self.domain = domain
self.debug = debug
def login(self, password):
self.__log("\"{domain}\\{user}\" logging on".format(domain=self.domain, user=self.username))
result = windll.advapi32.LogonUserW(
c_wchar_p(self.username),
c_wchar_p(self.domain),
c_wchar_p(password),
c_ulong(WindowsAuthentication.Logon32.LOGON32_LOGON_NETWORK),
c_ulong(WindowsAuthentication.Logon32.LOGON32_PROVIDER_DEFAULT),
pointer(self.token)
)
if result:
self.__log("\"{domain}\\{user}\" logged on".format(domain=self.domain, user=self.username))
else:
self.__log("\"{domain}\\{user}\" failed to login, error {err}".format(domain=self.domain, user=self.username, err=windll.kernel32.GetLastError()))
return True if result else False
def logoff(self):
if self.token.value != None:
self.__log("Closing token {token}".format(token=self.token.value))
windll.kernel32.CloseHandle(self.token)
else:
self.__log("No user token to logoff")
def __log(self, s):
if self.debug:
print s
def main():
from sys import argv, stdout, stderr
from getpass import getpass
if len(argv) != 3:
stderr.write("Usage: logonuser.py username domain\n")
return 1
auth = WindowsAuthentication(argv[1], argv[2], debug=True)
password = getpass("Password:")
result = auth.login(password)
print "Autentication {result}".format(result="succeeded" if result else "failed")
print "Press any key to logoff..."
raw_input()
auth.logoff()
return 0 if result else 1
if __name__ == "__main__":
exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.