running a command as a super user from a python script

后端 未结 8 1168
别跟我提以往
别跟我提以往 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:18

    I used this for python 3.5. I did it using subprocess module.Using the password like this is very insecure.

    The subprocess module takes command as a list of strings so either create a list beforehand using split() or pass the whole list later. Read the documentation for more information.

    What we are doing here is echoing the password and then using pipe we pass it on to the sudo through '-S' argument.

    #!/usr/bin/env python
    import subprocess
    
    sudo_password = 'mysecretpass'
    command = 'apach2ctl restart'
    command = command.split()
    
    cmd1 = subprocess.Popen(['echo',sudo_password], stdout=subprocess.PIPE)
    cmd2 = subprocess.Popen(['sudo','-S'] + command, stdin=cmd1.stdout, stdout=subprocess.PIPE)
    
    output = cmd2.stdout.read().decode() 
    
    0 讨论(0)
  • 2020-11-28 07:20

    Try giving the full path to apache2ctl.

    0 讨论(0)
提交回复
热议问题