Jérôme Belleman
Home  •  Tools  •  Posts  •  Talks  •  Travels  •  Graphics  •  About Me

Stopping a System with SSH Clients from Sleeping

23 Dec 2019

All it used to take was write a simple script in /etc/pm/sleep.d/ and have it exit non-zero if there were SSH clients. Things are now different with systemd.

1 Towards a Different Approach

I realised looking at the logs that this had come into the hands of systemd and this took me then to the systemd-sleep man page referring to /lib/systemd/system-sleep/. While I thought scripts in this directory would be treated the same way as those in /etc/pm/sleep.d/, it appears not to be the case. All the man page suggests is that sleeping will not happen until the scripts have finished running, which is a different behaviour from refusing to sleep if one of them exits non-zero. As it turns out, the same man page suggested one shouldn't use this directory anyway but instead resort to the inhibitor interface.

2 The Inhibitor Interface

The idea is to use the systemd-inhibit command, passing it a command line. Until this command line has completed, systemd-inhibit will hold a lock preventing the system from going to sleep. Now while it would have been straightforward to have the system check whether or not there are connected SSH clients every time it intends to sleep, I found it more convoluted to acquire a lock when an SSH client connects.

3 A Solution Around a Python Script

As always when I start writing what becomes more than a one-liner in a shell script, I end up deciding that I'm better off doing it in Python. I wrote the sshinhibit script which runs systemd-inhibit when logging in if it doesn't run already and kills it when logging out if it's the last SSH client that's about to hang up.

4 References