One of the ways that I've done this is by masking the systemd
targets, which prevents certain actions from being performed, regardless of who enters the command. For example, to prevent the system from being shutdown, you can do this:
sudo systemctl mask poweroff.target
Now any attempt to shutdown the system via sudo shutdown
or sudo systemctl shutdown
will silently fail. The same can be done with halting and reboots:
sudo systemctl mask runlevel0.target
sudo systemctl mask halt.target
sudo systemctl mask runlevel6.target
sudo systemctl mask reboot.target
Note: runlevel6
is equivalent to reboot
, and runlevel0
is equivalent to shutdown
and halt
.
To undo this, these commands can be run again, but with unmask
:
sudo systemctl unmask runlevel0.target
sudo systemctl unmask shutdown.target
sudo systemctl unmask halt.target
sudo systemctl unmask runlevel6.target
sudo systemctl unmask reboot.target
With this in mind, now you can write a script that is executable only for people with sudo
access:
#!/bin/bash
## Determine the operation to run (mask | unmask)
op=mask
if [[ $1 = unmask ]]
then
op=unmask
fi
## Set the targets we want to mask
declare -a arr=("runlevel0" "runlevel6" "shutdown" "reboot" "halt")
## Run the commands
for i in "${arr[@]}"
do
cmd=$( sudo systemctl $op $i.target )
echo "$i :: $op"
done
WARNING: This code will work, but it's pretty rough. Be sure to sanity check it with a VM or somewhere "safe" before running it on a production box.
Now you can have this script run to mask the targets after booting up, and shutdown/reboot like this:
sudo ~./setTargetMask.sh unmask
sudo shutdown now
Note: Feel free to call the script whatever you'd like.