You cannot make a bash script that runs setuid. However, you can make use of sudo
(or similar programs, like calife) to ensure they are run with root privileges.
There are two basic approaches to do this.
Lets suppose your script is called reset-swap
and does:
#!/bin/sh
swapoff /dev/sdb
shred -n0 -z /dev/sdb
mkswap /dev/sdb
swapon /dev/sdb
Option A: would be to let any user to run these individual commands, and prefix them with sudo:
#!/bin/sh
sudo swapoff /dev/sdb
sudo shred -n0 -z /dev/sdb
sudo mkswap /dev/sdb
sudo swapon /dev/sdb
and add on /etc/sudoers
a series of lines which let everyone do that:
ALL ALL = NOPASSWD: /sbin/swapoff /dev/sdb
ALL ALL = NOPASSWD: shred -n0 -z /dev/sdb
ALL ALL = NOPASSWD: mkswap /dev/sdb
ALL ALL = NOPASSWD: swapon /dev/sdb
However, while the actions specified may be safe to be done by everyone as done by the script, it might not be so independently. For example mkswap
checks that the swap partition is not mounted before processing it, but shred
would happily wipe a mounted swap partition.
Thus, it would be preferable to use
Option B: let only that script to be run with sudo.
ALL ALL = NOPASSWD: /usr/local/bin/reset-swap
You would then call it as sudo reset-swap
rather than reset-swap
. If you get fancy, the script could elevate itself if it wasn't run as root, letting it be run without specifying the sudo
prefix:
#!/bin/sh
if [ "`id -u`" -ne 0 ]; then
echo "Switching from `id -un` to root"
exec sudo "$0"
exit 99
fi
swapoff /dev/sdb
shred -n0 -z /dev/sdb
mkswap /dev/sdb
swapon /dev/sdb
Last, let me finish with a couple of points from the sudo lecture: Think before you type, With great power comes great responsibility.