12

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.

3
  • 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
    Commented Jul 19, 2016 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 Commented Jul 19, 2016 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
    Commented Jul 19, 2016 at 18:43

1 Answer 1

23

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'
2
  • 2
    Perfect! Thanks so much. Would upvote but need more rep for that :) Commented Jul 19, 2016 at 16:23
  • 1
    @JayWilliams: I upvoted on your behalf :-)
    – Tom Taylor
    Commented Nov 8, 2021 at 5:39

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.