Sudo renice in python

All in all, it is well answered. Linux doesn't allow unprivileged users to downgrade PIDs and run things as root - it's a worm gang of its own.

Here are my specifics: I have a user account that manages multiple processes with no password privileges sudo

for renice

and several other commands that it uses. I also have a script that is a common entry point for all users on this system. This script can run normal user programs as well as processes controlled by a special account. Thus, a script, when run with a specific option, should renice

if it can, but not silently if it cannot.

The code I have for this looks like this:

subprocess.Popen(["sudo", "renice", "-20", str(process.pid)],
#                shell = True,
                 stdout = subprocess.DEVNULL,
                 stderr = subprocess.STDOUT)

      

If I have it shell = True

commented out the process gets its new appeal, but if I run as an unprivileged user it sudo

throws out my password prompt and ruins my output to the terminal. The keys become invisible and everything becomes silly. If I uncomment shell = True

I am not getting terminal output. However, the process does not change its appeal, even if I run it as root.

The corrupted terminal output can be boiled down to the terminal emulator I'm using (haven't tried it with another), but I want to combine these behaviors. Silence from sudo

, no matter what, but subtlety will change if the user can successfully execute sudo.

Any pointers?

+3


source to share


1 answer


I guess because it sudo

requires a TTY
even if no password is needed.

Try one thing:

import os
import pty
import subprocess

master, slave = pty.openpty()
p = subprocess.Popen(
    ["sudo", "id", "-a"],
    stdin=slave, stdout=slave, stderr=slave
)
os.close(slave)

output = os.read(master, 1026)
os.close(master)
print(output)

      



The above code should print something like uid=0(root) gid=0(root) groups=0(root)

. If so, replace id

with renice

, remove unnecessary ones os.read

, and you should be good.

Update: In the OP's case, it failed for a different reason. By adding start_new_session=True

in Popen

if it doesn't work for unprivileged users and will succeed as root.

+2


source







All Articles