How to run python script with elevated privilege on windows

前端 未结 11 1390
臣服心动
臣服心动 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:12

    This worked for me:


    import win32com.client as client
    
    required_command = "cmd" # Enter your command here
    
    required_password = "Simple1" # Enter your password here
    
    def run_as(required_command, required_password):
        shell = client.Dispatch("WScript.shell")
        shell.Run(f"runas /user:administrator {required_command}")
        time.sleep(1)
        shell.SendKeys(f"{required_password}\r\n", 0)
    
    
    if __name__ = '__main__':
        run_as(required_command, required_password)
    

    Below are the references I used for above code: https://win32com.goermezer.de/microsoft/windows/controlling-applications-via-sendkeys.html https://www.oreilly.com/library/view/python-cookbook/0596001673/ch07s16.html

提交回复
热议问题