Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running commands from within python that need root access

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.

like image 633
myusuf3 Avatar asked Jun 03 '11 15:06

myusuf3


1 Answers

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 (using the visudo command):

# 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.

like image 116
jathanism Avatar answered Oct 01 '22 23:10

jathanism