Skip to content

Always Run Script As Root

Shell scripts (often referred to bash scripting, even though it's not necessarily bash) are a great way to automate certain things. Every now and then those scripts have to be run with privileges - in order to, say, register a network interface alias or bind a low-port.

Force Root

# ensure running as root
if [ "$(id -u)" != "0" ]; then
  exec sudo "$0" "$@"
fi

This allows me to call a script either with sudo ./the-script.sh or simply ./the-script.sh and thus not have to add sudo in front of all commands within the script.

Automatic Root

If you want to get rid of having to enter a password for a specific script, sudoers is your friend:

  1. open terminal
  2. run visudo
  3. move down to the end of the file
  4. press i (for "insert")
  5. add username host = (root) NOPASSWD: command (which can be rrehm ALL = (root) NOPASSWD: /usr/local/bin/the-script.sh)
  6. press ESC (escape)
  7. press : (colon to enter command mode)
  8. write wq (for "write quit")
  9. press enter

Since you won't have to enter your root password anymore when running the-script.sh, you want to make sure that only root can edit the file so nobody can abuse this script to run arbitrary commands as root:

  1. open terminal
  2. run sudo chown root:wheel /usr/local/bin/the-script.sh
  3. run sudo chmod u+rwx /usr/local/bin/the-script.sh (to allow root reading, writing and executing)
  4. run sudo chmod go-w+rx /usr/local/bin/the-script.sh (to allow everyone to execute and read, but writing)

and that's it, run the-script.sh in the terminal, as root, without having to enter a password.

Comments

Display comments as Linear | Threaded

No comments

The author does not allow comments to this entry