Disconnect idle SSH clients using built-in client alive mechanism.
OpenSSH server configuration
/etc/ssh/sshd_config OpenSSH server configuration file to define
ClientAliveInterval timeout interval in seconds and ensure that
ClientAliveCountMax number of client alive messages is set to zero - indicating that server will terminate session immediately after defined timeout interval without receiving any messages back from the client.
$ sudo vim /etc/ssh/sshd_config [...] ClientAliveInterval 900 ClientAliveCountMax 0 [...]
The above configuration will ensure that idle session will be disconnected after 15 minutes of inactivity.
Remember to reload OpenSSH server configuration.
$ sudo systemctl reload ssh
User will see connection closed by remote host message after server terminates connection due to session inactivity.
[email protected]:~$ ssh backup-server Last login: Sat Aug 25 20:17:17 2018 from 192.0.2.26 [email protected]:~$ Connection to backup-server closed by remote host. Connection to backup-server closed.
Server will log message that there was a timeout as client is not responding.
[...] Aug 25 20:56:24 backup-server sshd: Accepted publickey for milosz from 192.0.2.26 port 51040 ssh2: RSA SHA256:DbA657nx9z4P3yjQuRf7LtNN8en/BaypMYeeCxS6OYG Aug 25 20:56:24 backup-server sshd: pam_unix(sshd:session): session opened for user milosz by (uid=0) Aug 25 20:11:24 backup-server systemd-logind: New session 53 of user milosz. Aug 25 21:11:29 backup-server sshd: Timeout, client not responding. Aug 25 21:11:29 backup-server sshd: pam_unix(sshd:session): session closed for user milosz Aug 25 21:11:29 backup-server systemd-logind: Removed session 53. [...]
OpenSSH client configuration
You should use terminal multiplexer like
screen, but if you don't want to be disconnected by the OpenSSH server due to session inactivity, then edit local
~/.ssh/config client configuration file to define
ServerAliveInterval time interval between keep alive messages.
Host * ServerAliveInterval 60 ServerAliveCountMax 2
The above configuration will instruct client to send keep alive every minute, so it will circumvent timeout interval defined in server configuration.
The second option
ServerAliveCountMax will ensure that client will disconnect after two minutes without receiving any messages from the server (on third consecutive missing response to the keep alive message).
You can also specify these options using command-line parameters.
$ ssh -o ServerAliveInterval=60 -o ServerAliveCountMax=2 backup-server
User will see server is not responding message after the client terminates connection.
[email protected]:~$ ssh backup-server Last login: Sat Aug 25 20:17:17 2018 from 192.0.2.26 [...] Timeout, server backup-server not responding.