0

I have made a systemd service which performs some actions just before the machine shuts down. Its unit file is:

[Unit]
Before=shutdown.target
DefaultDependencies=no

[Service]
Type=simple
ExecStart=/opt/demo.sh
TimeoutSec=infinity

[Install]
WantedBy=shutdown.target

Currently, the script runs before the machine loses network connection, but after SSH connections are closed, and if I try to reconnect, it fails with “Connection refused” error. I would prefer keeping SSH connection until the script itself terminates (for instance to be able to tail -f /var/log/syslog its execution.)

How do I force to run the script before SSH server closes?

1

You could achieve required result by using a systemd unit as below:

[Unit]
Description=Service to run on shutdown before any other services
After=default.target

[Service]
Type=oneshot
ExecStart=/bin/true
ExecStop=/opt/demo.sh
RemainAfterExit=yes
TimeoutStopSec=0

[Install]
WantedBy=default.target

systemd stop's services based on their dependency in reverse order. So above service starts /bin/true after system reached default.target and your script /opt/demo.sh on stop/shutdown. Based on your requirement, you would want to tweak TimeoutStopSec, currently it's set to never timeout (instead of default 90 sec)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.