in /etc/ssh/sshd_config
# default values
ClientAliveInterval 0
ClientAliveCountMax 3
If you set ClientAliveInterval
to 600 {seconds} along with ClientAliveCountMax
to 0 then that will close any SSH session that has been idle for 10 minutes. By using this mechanism you could have any SSH session cleanly close after a specific timeout or idle period of your choosing. Then check to see if there are any SSH sessions or processes present and if not then do a shutdown.
Recommend you also read up on those two SSH parameters before using them to be sure,
https://man.openbsd.org/sshd_config
What do options `ServerAliveInterval` and `ClientAliveInterval` in sshd_config do exactly?
because someone doesn't believe me... edit /etc/ssh/sshd_config
to have ClientAliveInterval 61
and ClientAliveCountMax 0
and then have the below script run via crontab every minute and watch your machine shut down
#!/bin/bash
ssh_idle_shutdown.bash
the first num (a) in file /var/run/sshidleshutdown.txt is 0 or 1 based on if a ssh connection has happened
if a == 1 and count == 0 then do something
if [ ! -f /var/run/sshidleshutdown.txt ]
then
echo 0 > /var/run/sshidleshutdown.txt
fi
count=netstat -tnpa | grep 'ESTABLISHED.*sshd' | wc -l
str=head /var/run/sshidleshutdown.txt
astr=${str:0:1}
a=$((astr))
if [ $a -eq 0 ] && [ $count -gt 0 ]
then
echo 1 > /var/run/sshidleshutdown.txt
elif [ $a -eq 1 ] && [ $count -eq 0 ]
then
echo -n "ssh idle condition met system shutdown called at " >> /var/log/sshidleshutdownlog.txt
date >> /var/log/sshidleshutdownlog.txt
rm -f /var/run/sshidleshutdown.txt
execute /sbin/shutdown
fi
put this in /etc/crontab
1 * * * * * root /path_to/ssh_idle_shutdown.bash
and also do
chown root.root /path_to/ssh_idle_shutdown.bash
chmod 700 /path_to/ssh_idle_shutdown.bash
this is letting the SSH server identify what idle sessions are, and then the ssh server is closing them. Once we have seen at least one established ssh session then we begin checking until no ssh sessions are left via netstat, because the ssh server will have closed idle sessions based on ClientAlive Interval
and ClientAliveCountMax
in sshd_config
. Adjust ClientAliveInterval
and /etc/crontab
frequency for running this ssh_idle_shutdown.bash
accordingly.
timeoutd
which would log out users who had been idle for a configurable amount of time. It used to be pretty popular to stop users from hogging scarce resources like modem dial-in lines. I haven't seen it for many years and I don't think it's maintained any more. Anyway if you could find that and recompile it for a modern distro (or find an alternative that does the same thing), you could shutdown when there are no ssh sessions logged in. – cas Oct 20 '21 at 15:32