views:

62

answers:

3

I have written a bash script for use on my ubuntu box. Now I would like to prevent running this script under my own user and only able to run it as root (sudo).

Is there a possibility to force this. Can I somehow let my script ask for root permissions if I run it under my own username?

+1  A: 
sudo chown root yourcode
sudo chmod 500 yourcode

Voila!

mkoistinen
A: 

You can change the permissions, so that only root can execute it. Or you could use whoami command and in case that it isn't root force sudo.

Nuz
+3  A: 

I have a standard function I use in bash for this very purpose:

# Check if we're root and re-execute if we're not.
rootcheck () {
    if [ $(id -u) != "0" ]
    then
        sudo "$0" "$@"  # Modified as suggested below.
        exit $?
    fi
}

There's probably more elegant ways (I wrote this AGES ago!), but this works fine for me.

JUST MY correct OPINION
Possibly `exec sudo "$0" "$@"` to avoid problems with spaces in arguments, and avoid have the first execution hanging around?
Douglas Leeder
Yeah, that would be a decided improvement. I'll update the answer to reflect it.
JUST MY correct OPINION
Note that if it's run as a function like this, you need to pass in the script's parameters (i.e. run it with `rootcheck "$@"`). Or you can just put the if block inline rather than in a function. Also, this should be done very early in the script, as anything before it will be run twice (once normally, once as root).
Gordon Davisson
I do it first thing in the script, so yeah. Early is right.
JUST MY correct OPINION
It's sometimes good to run sanity checks (e.g. does the file in question exist?) before sudo'ing -- I tend to do this by starting the script with something like `if [[ $1 == "--no-sanity-checks" ]]; then shift; else run sanity checks; fi` and then modify the sudo command to `exec sudo "$0" --no-sanity-checks "$@"`
Gordon Davisson

related questions