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

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.

  • If you have a working root account and the user has access to the root password, why not just give them sudo access? They already have the power to break anything they can possibly break. You can also give them sudo access to run your script only. Would that be a decent workaround? – terdon Jul 19 '16 at 16:04
  • Basically multiple people use the account, but only some need root access in the python script and therefore I don't want to open a security hole where the script has root access by typing in the common password(that everyone knows) if that makes sense. Knowing me it probably doesn't – Jay Williams Jul 19 '16 at 16:28
  • thegeekdiary.com/what-is-suid-sgid-and-sticky-bit consider using the SUID bit on your script; if only part of the script requires root privilege then consider extracting that part out into a second script. create a new group id specifically for the script execution and have only those users who should be able execute it part of the group. The script needing root privilege is the only one should be owned by root with suid set. This would prevent ever having to give out the root password. – ron Jul 19 '16 at 18:43

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'
  • 1
    Perfect! Thanks so much. Would upvote but need more rep for that :) – Jay Williams Jul 19 '16 at 16:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.