Executing commands from inside python requiring root access

Recently, I have been playing with a subprocess. Like me more and more; I need root access. I was wondering if there is an easy way to enter the root password for the command that needs it with the subprocess module. Therefore, when I am prompted to enter my script password and provide it and execute the command. I know this is a bad practice when the code is run, isolated, and separated from the rest of the system; I also do not want to work as root.

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

Thanks.

+6
source share
1 answer

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

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

You must first create a group called tcpdumpers . Then change /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 as follows:

 % sudo tcpdump 

From there, you can easily run this command as subprocess .

This eliminates the need to hard-code the root password in the program code and provides detailed control over who can perform any action with root privileges on your system.

+10
source

Source: https://habr.com/ru/post/889709/


All Articles