Write a Script That Runs Automatically During Boot
This How-To guide will walk through the process of creating a script that is run automatically at boot. This could be directly relevant to an end-user application that requires setting up servers, setting up environment variables, or enabling services. For this guide we will create and enable a WatchDog service that automatically reboots the system upon encountering an unexpected hardware or software hangup. This could be very useful for mission critical applications that do not have user intervention as an option.
First, we will need to create a script for enabling the WatchDog. The WatchDog is enabled automatically when the timeout setting is set which is nice because it keeps this script nice and short. This can be done using the Vi Text Editor:
Once the editor is open, fill in the contents of the file so that it is the same as below:
Vi Text Editor: enableWD
#!/bin/bash wdctl -s 2CODE
The vi text editor begins in "Command Mode" and you must first hit the 'i' key in order to enter "Insert Mode". Using the arrow keys to navigate, make the necessary changes and then hit ESC to go back to "Command mode". Now enter ":wq" to write the file and quit.
Pro Tip: Use the right click on your mouse to paste. This will only work if you are in "Insert Mode" first.
Once the script is saved and closed, ensure that the file is executable by all users by using the following commands to modify the file's permissions:
chmod a+x /home/root/enableWDCODE
Now we need a systemd service that runs the script during boot. Systemd services are managed through Unit files which we will create by using the Vi Text Editor again:
Once the editor is open, fill in the contents of the Unit file so that it is the same as below:
Vi Text Editor: enableWD.service
[Unit] Description=Watchdog Enable Service After=basic.target [Service] Type=oneshot RemainAfterExit=yes ExecStart=/home/root/enableWD start [Install] WantedBy=default.targetCODE
Once the Unit file is saved and closed we can enable the service to run during boot with the following:
systemctl enable enableWDCODE
In order for our change to take effect lets reboot the system:
Once booted back into Linux and logged in as root, try triggering a kernel panic with the following command. The WatchDog should initiate a reboot about 2 seconds after the panic starts.
echo c > /proc/sysrq-triggerCODE
If you desire to disable the service we just created, use this command!
systemctl disable enableWD