I have a server that runs Debian and sshd on it, and in case I need to reboot the server my SSH session hangs at client side until TCP timeout. I assume this is because when sshd
is being terminated it does not explicitly close open SSH sessions to the host. What should I do to make sshd
first disconnect everyone, then terminate itself as normal? So far I don't see a parameter in man sshd_config
that's related to shutsown behavior.
When you shutdown or reboot your system,
systemd
tries to stop all services as fast as it can. That involves bringing down the network and terminating all processes that are still alive -- usually in that order. So when systemd kills the forked SSH processes that are handling your SSH sessions, the network connection is already disabled and they have no way of closing the client connection gracefully.Your first thought might be to just kill all SSH processes as the first step during shutdown, and there are quite a few systemd service files out there that do just that.
But there is of course a neater solution (how it's "supposed" to be done):
systemd-logind
.systemd-logind
keeps track of active user sessions (local and SSH ones) and assigns all processes spawned within them to so-called "slices". That way, when the system is shut down, systemd can just SIGTERM everything inside the user slices (which includes the forked SSH process that's handing a particular session) and then continue shutting down services and the network.systemd-logind
requires a PAM module to get notified of new user sessions and you'll needdbus
to useloginctl
to check its status, so install both of those:Be sure your
/etc/ssh/sshd_config
is actually going to use the module withUsePAM yes
.This is something you need to set on the client side, not the server side. Edit your
~/.ssh/config
to containThis means that after 15 seconds of inactivity, your client will send a message to the server. If it doesn't get any response, it will try again up to 5 times, and when it still doesn't get an answer, it'll close the session.
This behaviour is reported on this Debian Bug, you only need to setup correctly the shutdown scripts shiped with the package because, automatically, they aren't copied by default:
You can specify the options that Jenny D talked about in her answer just for one ssh command, such as
if you do that often, you can script it.
Works for me with lshd. So the solution would be
sadly serverfault didn't let me answer in thread cause by too few points since years. But I don't need to spam in other blogs to get the unlocking ^^... so as dedicated answer:
As Rfraile mentioned
works. To be using it without reboot the instance/server you should do additional tasks:
so the service is registered and started and systemd needs to stop it for reboot/shutdown purposes.