Change to sudo user within a python script

前端 未结 8 1875
挽巷
挽巷 2020-11-29 05:33

I have a problem. I am writing a piece of software, which is required to perform an operation which requires the user to be in sudo mode. running \'sudo python filename.py\'

8条回答
  •  醉梦人生
    2020-11-29 05:53

    I've recently dealt with this problem while making a system installation script. To switch to superuser permissions, I used subprocess.call() with 'sudo':

    #!/usr/bin/python
    
    import subprocess
    import shlex
    import getpass
    
    print "This script was called by: " + getpass.getuser()
    
    print "Now do something as 'root'..."
    subprocess.call(shlex.split('sudo id -nu'))
    
    print "Now switch back to the calling user: " + getpass.getuser()
    

    Note that you need to use shlex.split() to make your command usable for subprocess.call(). If you want to use the output from a command, you can use subprocess.check_output(). There is also a package called 'sh' (http://amoffat.github.com/sh/) that you can use for this purpose.

提交回复
热议问题