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" "$@"

This allows me to call a script either with sudo ./ or simply ./ 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/
  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, 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/
  3. run sudo chmod u+rwx /usr/local/bin/ (to allow root reading, writing and executing)
  4. run sudo chmod go-w+rx /usr/local/bin/ (to allow everyone to execute and read, but writing)

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


Display comments as Linear | Threaded

No comments

The author does not allow comments to this entry