The following approach seems to run a script on shutdown only, and not on reboot. You can edit the
systemd-poweroff.service file as follows:
sudo systemctl edit --full systemd-poweroff.service
[Service] section, you can then add an
This way, the script will not be executed if you shutdown the system with
halt however. To handle this case, you can add the same line to
Note that in this approach the config file shown in the question is not used.
EDIT: a possible shortcoming in the previous approach, is that the script to be executed contains an
ssh command, which may not work right before shutting down the system (systemd may already have stopped necessary network services). The approach below tries to avoid this.
For this solution, I created a
pfsenseshutdown.service unit with the following contents
Description=PFSense Shutdown script
When starting the shutdown procedure, this file seems to cause the
ExecStart line to be executed right away, causing the file
/dev/shm/shuttingdown to exist (the
/dev/shm directory is a memory file system, so it will be cleared after a reboot).
Now, to make sure that your script is executed before the network is completely de-initialized, I ran
systemctl edit --full networking.service
Originally, it contained the following
ExecStop line on my ubuntu 16.04 virtual machine:
ExecStop=/sbin/ifdown -a --read-environment
This line was replaced by a version that first runs your script, in this example:
ExecStop=/path/to/script/pfsenseshutdown.sh && /sbin/ifdown -a --read-environment
pfsenseshutdown.sh script, then tests if the file in
/dev/shm exists, and performs the ssh command accordingly. I also added a small
sleep command: systemd does many things in parallel, and this hopefully helps prevent the test from failing because the file does not exist yet.
if [ -e /dev/shm/shuttingdown ] ; then
# Your ssh command here