Guest User

Untitled

a guest
Mar 21st, 2018
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.38 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8; mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
  3. # vim: fileencoding=utf-8 tabstop=4 expandtab shiftwidth=4
  4.  
  5. """User Access Control for Microsoft Windows Vista and higher. This is
  6. only for the Windows platform.
  7.  
  8. This will relaunch either the current script - with all the same command
  9. line parameters - or else you can provide a different script/program to
  10. run. If the current user doesn't normally have admin rights, he'll be
  11. prompted for an admin password. Otherwise he just gets the UAC prompt.
  12.  
  13. Note that the prompt may simply shows a generic python.exe with "Publisher:
  14. Unknown" if the python.exe is not signed.
  15.  
  16. This is meant to be used something like this::
  17.  
  18. if not pyuac.isUserAdmin():
  19. return pyuac.runAsAdmin()
  20.  
  21. # otherwise carry on doing whatever...
  22.  
  23. See L{runAsAdmin} for the main interface.
  24.  
  25. """
  26.  
  27. import sys, os, traceback, types
  28.  
  29. def isUserAdmin():
  30. """@return: True if the current user is an 'Admin' whatever that
  31. means (root on Unix), otherwise False.
  32.  
  33. Warning: The inner function fails unless you have Windows XP SP2 or
  34. higher. The failure causes a traceback to be printed and this
  35. function to return False.
  36. """
  37.  
  38. if os.name == 'nt':
  39. import win32security
  40. # WARNING: requires Windows XP SP2 or higher!
  41. try:
  42. adminSid = win32security.CreateWellKnownSid(win32security.WinBuiltinAdministratorsSid, None)
  43. return win32security.CheckTokenMembership(None, adminSid)
  44. except:
  45. traceback.print_exc()
  46. print("Admin check failed, assuming not an admin.")
  47. return False
  48. else:
  49. # Check for root on Posix
  50. return os.getuid() == 0
  51.  
  52. def runAsAdmin(cmdLine=None, wait=True):
  53. """Attempt to relaunch the current script as an admin using the same
  54. command line parameters. Pass cmdLine in to override and set a new
  55. command. It must be a list of [command, arg1, arg2...] format.
  56.  
  57. Set wait to False to avoid waiting for the sub-process to finish. You
  58. will not be able to fetch the exit code of the process if wait is
  59. False.
  60.  
  61. Returns the sub-process return code, unless wait is False in which
  62. case it returns None.
  63.  
  64. @WARNING: this function only works on Windows.
  65. """
  66.  
  67. if os.name != 'nt':
  68. raise RuntimeError("This function is only implemented on Windows.")
  69.  
  70. import win32api, win32con, win32event, win32process
  71. from win32com.shell.shell import ShellExecuteEx
  72. from win32com.shell import shellcon
  73.  
  74. python_exe = sys.executable
  75.  
  76. if cmdLine is None:
  77. cmdLine = [python_exe] + sys.argv
  78. elif type(cmdLine) not in (types.TupleType,types.ListType):
  79. raise ValueError("cmdLine is not a sequence.")
  80. cmd = '"%s"' % (cmdLine[0],)
  81. # XXX TODO: isn't there a function or something we can call to massage command line params?
  82. params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]])
  83. cmdDir = ''
  84. showCmd = win32con.SW_SHOWNORMAL
  85. lpVerb = 'runas' # causes UAC elevation prompt.
  86.  
  87. # print "Running", cmd, params
  88.  
  89. # ShellExecute() doesn't seem to allow us to fetch the PID or handle
  90. # of the process, so we can't get anything useful from it. Therefore
  91. # the more complex ShellExecuteEx() must be used.
  92.  
  93. # procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd)
  94.  
  95. procInfo = ShellExecuteEx(nShow=showCmd,
  96. fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
  97. lpVerb=lpVerb,
  98. lpFile=cmd,
  99. lpParameters=params)
  100.  
  101. if wait:
  102. procHandle = procInfo['hProcess']
  103. obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
  104. rc = win32process.GetExitCodeProcess(procHandle)
  105. #print "Process handle %s returned code %s" % (procHandle, rc)
  106. else:
  107. rc = None
  108.  
  109. return rc
  110.  
  111. def test():
  112. """A simple test function; check if we're admin, and if not relaunch
  113. the script as admin.""",
  114. rc = 0
  115. if not isUserAdmin():
  116. print("You're not an admin.", os.getpid(), "params: ", sys.argv)
  117. #rc = runAsAdmin(["c:\\Windows\\notepad.exe"])
  118. rc = runAsAdmin()
  119. else:
  120. print("You are an admin!", os.getpid(), "params: ", sys.argv)
  121. rc = 0
  122. x = input('Press Enter to exit.')
  123. return rc
  124.  
  125.  
  126. if __name__ == "__main__":
  127. res = test()
  128. sys.exit(res)
Add Comment
Please, Sign In to add comment