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
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:
- open terminal
- run
visudo
- move down to the end of the file
- press
i
(for "insert") - add
username host = (root) NOPASSWD: command
(which can berrehm ALL = (root) NOPASSWD: /usr/local/bin/the-script.sh
) - press
ESC
(escape) - press
:
(colon to enter command mode) - write
wq
(for "write quit") - 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:
- open terminal
- run
sudo chown root:wheel /usr/local/bin/the-script.sh
- run
sudo chmod u+rwx /usr/local/bin/the-script.sh
(to allow root reading, writing and executing) - 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.
The author does not allow comments to this entry
Comments
Display comments as Linear | Threaded