Python – Su as root and run command in one line

pythonsusudo

I need to su as root and run a command as a single line. This is for use in a python script. What I am looking for is:

$ su root [some-magic] sh /home/jay/script-that-needs-executing-as-root.sh
<script output>

This is on a public-ish ubuntu server. The account that this will be run on has no password, but has been set up so basically everything is unaccessable, apart from a python script which is read only, and in ~/.profile, at the end is

cd ~/py/main
python3 start.py
logout

So they have no real access to the server. Inside the python script I have got su working, so if it is needed the user can type shellasroot into the python script, enter root password and run commands, but I am looking for a way to do this programatically.


TL; DR – On an account without sudo privelages, I need to run a shell script, as root, in one line.

Best Answer

You can use the -c option of su to pass a single command.

su root -c 'sh /home/jay/script-that-needs-executing-as-root.sh'
Related Question