Running commands from within python that need root access

2024/11/14 12:31:56

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.

Answer

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.

https://en.xdnf.cn/q/72195.html

Related Q&A

How not to plot missing periods

Im trying to plot a time series data, where for certain periods there is no data. Data is loaded into dataframe and Im plotting it using df.plot(). The problem is that the missing periods get connected…

Disabling std. and file I/O in Python sandbox implementation

Im trying to set up a Python sandbox and want to forbid access to standard and file I/O. I am running the sandbox inside of a running Python server.Ive already looked at modules like RestrictedPython a…

Extract edge and communities from list of nodes

I have dataset which has more than 50k nodes and I am trying to extract possible edges and communities from them. I did try using some graph tools like gephi, cytoscape, socnet, nodexl and so on to v…

Why is this usage of python F-string interpolation wrapping with quotes?

Code in question:a = test# 1) print(f{a}) # test# 2) print(f{ {a} }) # {test}# 3) print(f{{ {a} }}) # {test}My question is, why does case two print those quotes?I didnt find anything explicitly in the…

Adding a matplotlib colorbar from a PatchCollection

Im converting a Shapely MultiPolygon to a PatchCollection, and first colouring each Polygon like so:# ldn_mp is a MultiPolygon cm = plt.get_cmap(RdBu) num_colours = len(ldn_mp)fig = plt.figure() ax = f…

Mac 10.6 Universal Binary scipy: cephes/specfun _aswfa_ symbol not found

I cant get scipy to function in 32 bit mode when compiled as a i386/x86_64 universal binary, and executed on my 64 bit 10.6.2 MacPro1,1.My python setupWith the help of this answer, I built a 32/64 bit …

python: numpy list to array and vstack

from scipy.io.wavfile import read filepath = glob.glob(*.wav) rates = [] datas = [] for fp in filepath:rate, data = read(fp)rates.append(rate)datas.append(data)I get a list datas which is :[array([0, 0…

Django Unittests Client Login: fails in test suite, but not in Shell

Im running a basic test of my home view. While logging the client in from the shell works, the same line of code fails to log the client in when using the test suite.What is the correct way to log the …

Icon overlay issue with Python

I found some examples and topics on this forum about the way to implement an icon overlay handler with Python 2.7 & the win32com package but it does not work for me and I dont understand why. I cre…

Comparing NumPy object references

I want to understand the NumPy behavior.When I try to get the reference of an inner array of a NumPy array, and then compare it to the object itself, I get as returned value False.Here is the example:I…