Guest User

Untitled

a guest
May 18th, 2017
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.16 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3.  
  4. import os
  5. import msvcrt
  6. import subprocess
  7.  
  8. # PyWin32
  9. import winerror, win32con, win32console
  10.  
  11. def runas(args, username, domain=None, password=None, savecred=False):
  12.     if domain is not None:
  13.         username = r"{}\{}".format(domain, username)
  14.     runas = os.path.join(os.environ['SystemRoot'], 'System32', 'runas.exe')
  15.     runas_args = [runas, '/user:{}'.format(username)]
  16.     if savecred or password is None:
  17.         runas_args.append('/savecred')
  18.  
  19.     if isinstance(args, (type(''), type(u''))):
  20.         runas_args.append(args)
  21.     else:
  22.         runas_args.append(subprocess.list2cmdline(args))
  23.  
  24.     if password is None:
  25.         p = subprocess.Popen(runas_args,
  26.                              creationflags=win32con.DETACHED_PROCESS)
  27.         return p.wait()
  28.  
  29.     if isinstance(password, bytes):
  30.         password = password.decode('utf-8')
  31.  
  32.     free_console = True
  33.     try:
  34.         win32console.AllocConsole()
  35.     except win32console.error as exc:
  36.         if exc.winerror != winerror.ERROR_ACCESS_DENIED:
  37.             raise
  38.         free_console = False
  39.  
  40.     try:
  41.         fdin = os.open('CONIN$', os.O_RDWR)
  42.         stdin = None
  43.         try:
  44.             stdin = win32console.PyConsoleScreenBufferType(
  45.                         msvcrt.get_osfhandle(fdin))
  46.             p = subprocess.Popen(runas_args, stdout=subprocess.PIPE)
  47.             while p.poll() is None:
  48.                 if p.stdout.read(1) == b":":
  49.                     records = []
  50.                     for c in u"{}\r".format(password):
  51.                         x = win32console.PyINPUT_RECORDType(
  52.                                 win32console.KEY_EVENT)
  53.                         x.Char = c
  54.                         x.KeyDown = True
  55.                         x.RepeatCount = 1
  56.                         records.append(x)
  57.                     stdin.WriteConsoleInput(records)
  58.                     break
  59.             return p.wait()
  60.         finally:
  61.             os.close(fdin)
  62.             if stdin is not None:
  63.                 # close the duplicate handle
  64.                 stdin.Close()
  65.     finally:
  66.         if free_console:
  67.             win32console.FreeConsole()
Add Comment
Please, Sign In to add comment