Running commands from within python that need root

2019-06-18 19:10发布

问题:

I have been playing around with subprocess lately. As I do more and more; I find myself needing root access. I was wondering if there is an easy way to enter the root password for a command that needs it with subprocess module. So when I am prompted for the password my script and provide it and run the command. I know this is bad practice by where the code will be running is sandboxed and separate from the rest of the system; I also dont want to be running as root.

I would really appreciate small example if possible. I know you can do this with expect, but i am looking something more python centric. I know pexpect exsists but its a bit overkill for this simple task.

Thanks.

回答1:

It would probably be best to leverage sudo for the user running the Python program. You can specify specific commands and arguments that can be run from sudo without requiring a password. Here is an example:

There are many approaches but I prefer the one that assigns command sets to groups. So let's say we want to create a group to allow people to run 'tcpdump' as root. So let's call that group tcpdumpers.

First you would create a group called tcpdumpers. Then modify /etc/sudoers:

# Command alias for tcpdump
Cmnd_Alias      TCPDUMP = /usr/sbin/tcpdump

# This is the group that is allowed to run tcpdump as root with no password prompt
%tcpdumpers     ALL=(ALL) NOPASSWD: TCPDUMP

Now any user added to the tcpdumpers group will be able to run tcpdump like this:

% sudo tcpdump 

From there you could easily run this command as a subprocess.

This eliminates the need to hard-code the root password into your program code, and it enables granular control over who can run what with root privileges on your system.