How to run python script with elevated privilege on windows

前端 未结 11 1391
臣服心动
臣服心动 2020-11-22 07:34

I am writing a pyqt application which require to execute admin task. I would prefer to start my script with elevate privilege. I am aware that this question is asked many ti

11条回答
  •  太阳男子
    2020-11-22 08:01

    Here is a solution which needed ctypes module only. Support pyinstaller wrapped program.

    #!python
    # coding: utf-8
    import sys
    import ctypes
    
    def run_as_admin(argv=None, debug=False):
        shell32 = ctypes.windll.shell32
        if argv is None and shell32.IsUserAnAdmin():
            return True
    
        if argv is None:
            argv = sys.argv
        if hasattr(sys, '_MEIPASS'):
            # Support pyinstaller wrapped program.
            arguments = map(unicode, argv[1:])
        else:
            arguments = map(unicode, argv)
        argument_line = u' '.join(arguments)
        executable = unicode(sys.executable)
        if debug:
            print 'Command line: ', executable, argument_line
        ret = shell32.ShellExecuteW(None, u"runas", executable, argument_line, None, 1)
        if int(ret) <= 32:
            return False
        return None
    
    
    if __name__ == '__main__':
        ret = run_as_admin()
        if ret is True:
            print 'I have admin privilege.'
            raw_input('Press ENTER to exit.')
        elif ret is None:
            print 'I am elevating to admin privilege.'
            raw_input('Press ENTER to exit.')
        else:
            print 'Error(ret=%d): cannot elevate privilege.' % (ret, )
    

提交回复
热议问题