running a command as a super user from a python script

后端 未结 8 1224
别跟我提以往
别跟我提以往 2020-11-28 06:15

So I\'m trying to get a process to be run as a super user from within a python script using subprocess. In the ipython shell something like

proc = subproces         


        
8条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 07:03

    To run a command as root, and pass it the password at the command prompt, you could do it as so:

    import subprocess
    from getpass import getpass
    
    ls = "sudo -S ls -al".split()
    cmd = subprocess.run(
        ls, stdout=subprocess.PIPE, input=getpass("password: "), encoding="ascii",
    )
    print(cmd.stdout)
    

    For your example, probably something like this:

    import subprocess
    from getpass import getpass
    
    restart_apache = "sudo /usr/sbin/apache2ctl restart".split()
    proc = subprocess.run(
        restart_apache,
        stdout=subprocess.PIPE,
        input=getpass("password: "),
        encoding="ascii",
    )
    

提交回复
热议问题