I'm trying to think of a solution for a problem I have.
I have a server running sftp.
I sometime need to reboot this machine for updates and other maintenance but I don't want to wait for the precise moment it's inactive to run the reboot command. I'd like to be able to ask the server to reboot and wait for its last ssh connection to be active ended (if it can refuse new connection it would be a plus but it's not necessary).
Can I configure systemd or ssh so that sshd will suspend the reboot process as long as active connections are running toward the server.
This imply at least keeping my mount point, network, and ssh daemon running until active ssh session stop at which point the machine can restart.
I'm looking for a solution using either sshd or systemd configuration.
If the solution is a custom script I'll work on that but I would love to have an integrated solution.
1 Answer
You can connect to the server over SSH and see if anyone is logged in using the command who or the command w
if [[ -z $(ssh SERVERHOST-IP 'w -oh') ]]; then echo "No User Logged in"; else echo "User Connected"; fi
This will check if the command w -oh is empty which will check if any user is logged in.
You can use this to restart your server remotely when no more users are logged in.
while [ $(ssh SERVERHOST-IP 'w -oh|wc -l') -gt 0 ]; do sleep 1; echo "User Connected"; done && echo "Reboot server" && ssh -t SERVERHOST-IP 'sudo shutdown -r now'
- You may omit the
echocommands if you prefer. - Replace
SERVERHOST-IPwith your actual server IP address or hostname. who,wandwcare common commands in Linux and are most likely available to you.
You could use any of these command to:
- Create a custom shutdown command placed in
/usr/sbin - Create a custom
systemdshutdown routine
-
Thank you this is an interesting solution but if I have to script that I will use python. I do not want to maintains a bash script.Kiwy– Kiwy2023-04-27 14:43:33 +00:00Commented Apr 27, 2023 at 14:43
AllowUsers your_logintosshd_config, so even if something goes wrong you will be able to log in.