Quantcast
Linux Hacks

Linux Hack of The Week #2: Systemd Startup Scripts

Linux Hack: Systemd Startup Scripts

If you are an IoT user, sys admin or other Linux user then you have had a need to make a custom startup script. In the past you may have added a line to rc.local, inittab or a file in init.d. But systemd has taken over and now custom startup scripts are really easy to create. As an example, we’ll create a script that runs a DNS sniffer <github.com/joemcmanus/dnscloud> on boot.

Location

Depending on your particular flavor of Linux the location may differ, but on most including my Fedora 28 install it is in /usr/lib/systemd/system . You would copy or create your systemd service files in this location.

Format

Below is a file which we’ll name pysniff.service. Take a look then we’ll go through it line by line. Most of it is self explanatory, you’ll be an expert once you create a custom service or two.

[Unit] Description=Python DNS Sniffing Service
After=multi-user.target
[Service] type=oneshot
WorkingDirectory=/usr/local/scripts
ExecStart=/usr/local/scripts/pysniff.py wlan0 /data/dnsqueries.txt –pid
RestartSec=10s
Restart=always
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID

[Unit] : The section which contain individual unit definition info.
Description: Put the description of your process here.
After : Execute after this command/target
Before : Execute before this command/target

[Service] : This section contains configurations for this service
Type : What type of process; simple, oneshot, forking, etc.
PIDFile : A location for the PID file if the type is forking
ExecStart : The command used to to start  the process when systemctl start command is called
RestartSec : The delay to restart a process after it dies
Restart : Conditions on when to restart, always, on-failure, on-success, etc.
ExecReload : Command to restart the process
ExecStop : Command to stop the process

Installation

To enable the service you would run the command systemctl enable example.service .

Conclusion

This is just an introduction, there is much more you can do and more options for the systemd config files. But with just what you have read here you should be able to get going and troubleshoot any issues. Love these Linux hacks? Want other tips and hacks? Just leave me a comment with questions or feedback!

Joe McManus, CISO

Author Joe McManus, CISO

Joe is a Senior Cyber Security Researcher at CERT and a Professor at the University of Colorado College of Engineering where he teaches graduate courses in information security and forensics. Recently, Joe was the Director of Security at SolidFire, (acquired by NetApp [NTAP]). He is an avid cyclist, climber and leads the Automox security team.

More posts by Joe McManus, CISO

Leave a Reply