Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- import os
- import msvcrt
- import subprocess
- # PyWin32
- import winerror, win32con, win32console
- def runas(args, username, domain=None, password=None, savecred=False):
- if domain is not None:
- username = r"{}\{}".format(domain, username)
- runas = os.path.join(os.environ['SystemRoot'], 'System32', 'runas.exe')
- runas_args = [runas, '/user:{}'.format(username)]
- if savecred or password is None:
- runas_args.append('/savecred')
- if isinstance(args, (type(''), type(u''))):
- runas_args.append(args)
- else:
- runas_args.append(subprocess.list2cmdline(args))
- if password is None:
- p = subprocess.Popen(runas_args,
- creationflags=win32con.DETACHED_PROCESS)
- return p.wait()
- if isinstance(password, bytes):
- password = password.decode('utf-8')
- free_console = True
- try:
- win32console.AllocConsole()
- except win32console.error as exc:
- if exc.winerror != winerror.ERROR_ACCESS_DENIED:
- raise
- free_console = False
- try:
- fdin = os.open('CONIN$', os.O_RDWR)
- stdin = None
- try:
- stdin = win32console.PyConsoleScreenBufferType(
- msvcrt.get_osfhandle(fdin))
- p = subprocess.Popen(runas_args, stdout=subprocess.PIPE)
- while p.poll() is None:
- if p.stdout.read(1) == b":":
- records = []
- for c in u"{}\r".format(password):
- x = win32console.PyINPUT_RECORDType(
- win32console.KEY_EVENT)
- x.Char = c
- x.KeyDown = True
- x.RepeatCount = 1
- records.append(x)
- stdin.WriteConsoleInput(records)
- break
- return p.wait()
- finally:
- os.close(fdin)
- if stdin is not None:
- # close the duplicate handle
- stdin.Close()
- finally:
- if free_console:
- win32console.FreeConsole()
Add Comment
Please, Sign In to add comment