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
In the [Service]
section, you can then add an ExecStartPre
line:
ExecStartPre=/path/to/script/pfsenseshutdown.sh
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 systemd-halt.service
.
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
[Unit]
Description=PFSense Shutdown script
DefaultDedendencies=no
[Service]
Type=oneshot
ExecStart=/usr/bin/touch /dev/shm/shuttingdown
[Install]
WantedBy=systemd-halt.service systemd-poweroff.service
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
The 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.
#!/bin/bash
sleep 1
if [ -e /dev/shm/shuttingdown ] ; then
# Your ssh command here
fi
WantedBy=shtudown.target
instead ofWantedBy=multi-user.target
. I think you also have to change theExecStart
andExecStop
assignments.ExecStart=/path/to/script/pfsenseshutdown.sh
./dev/shm/
(is a memory file system, and is cleared when you boot). In thepfsenseshutdown.sh
script you could then look for that file to see if it's a reboot or shutdown.