Jeff
Jeff

Reputation: 7210

Python sudo privileges

I have a script (A.py) that will spawn new processes (B.py) dynamically but those scripts need to be created as root. If I run

$ python A.py

as a normal user, then when I run

>>> subprocess.Popen('sudo nohup python B.py &') 

I'll need to enter the root password to start. I don't really want to do that.


Now if I run the first script as root

$ sudo python A.py

then I'll be able to run

>>> subprocess.Popen('nohup python B.py &')

like normal. The thing that concerns me is a timeout period with the sudo and it will drop to normal privileges then when A.py want to spawn/kill a process it will ask for a password and stop working as intended.

  1. Will running sudo python A.py keep root privileges for the life of the script, or will it lose it with the sudo timeout (I believe default is 15min) like a normal terminal?
  2. Is there a better way of doing this?

Upvotes: -1

Views: 2805

Answers (2)

Chris Morgan
Chris Morgan

Reputation: 90882

You could have an additional script which would run python B.py, this script being owned by root, with the setuid flag set. (Alternatively, give B.py an appropriate shebang and make it executable directly.) Then running it at any time would run it as root. (You naturally then need to make sure it's protected so that it can only be run appropriately and can't execute arbitrary code, providing privilege escalation.)

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 362087

Will running sudo python A.py keep root privileges for the life of the script, or will it lose it with the sudo timeout (I believe default is 15min) like a normal terminal?

It will keep root privileges for the lifetime of the script.

Running commands don't have their root privileges revoked; that's not what the timeout does. The timeout simply controls how often a user has to enter their password when they do a sudo command. Since your now root-privileged script would simply execute nohup python B.py directly rather than sudo nohup python B.py the sudo timeout would not come into play.

Upvotes: 4

Related Questions