Last active
December 12, 2022 05:09
-
-
Save rammanokar/c1128918a1fab8cc45f458bedc58a337 to your computer and use it in GitHub Desktop.
Script to Shutdown Idle linux server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Unit] | |
Description=SSH idle shutdown | |
After=ssh.service | |
[Service] | |
ExecStart=/usr/bin/sshIdleShutdown.sh | |
Restart=on-failure | |
RestartSec=5s | |
[Install] | |
WantedBy=multi-user.target |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# create a script to shutdown the server if there is no active ssh connection | |
# for 30 minutes this script will be manged as system service | |
# save this script in /usr/bin/sshIdleShutdown.sh | |
# create service file in /usr/lib/systemd/system/sshIdleShutdown.service | |
# Install and enable service | |
# sudo systemctl daemon reload && sudo systemctl enable sshIdleShutdown.service | |
# start the service | |
# sudo systemctl start sshIdleShutdown.service | |
timeToShutdown=30 | |
while true; do | |
# check if there is an active ssh connection | |
if [[ $(pgrep -f "sshd: [^@]*@") ]]; then | |
# there is an active ssh connection | |
# reset the counter | |
echo 0 >/tmp/ssh_counter | |
echo "active ssh connection; counter reset" | |
else | |
# there is no active ssh connection | |
# increment the counter | |
counter=$(cat /tmp/ssh_counter) | |
counter=$((counter + 1)) | |
echo $counter >/tmp/ssh_counter | |
echo "no active ssh connection; counter incremented to $counter" | |
fi | |
# check if the counter is greater than 30 | |
if [[ $(cat /tmp/ssh_counter) -gt $timeToShutdown ]]; then | |
# the counter is greater than 30 | |
# shutdown the server | |
sudo init 0 | |
fi | |
sleep 60 | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment