/etc/systemd/system/ssh_watchdog.service
/usr/local/bin/ssh_watchdog.sh
Last active
September 15, 2024 14:57
-
-
Save audacioustux/f7461e44d4ab70725f1f8f0d368a584e to your computer and use it in GitHub Desktop.
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 Watchdog | |
[Service] | |
ExecStart=/usr/local/bin/ssh_watchdog.sh | |
Restart=always | |
[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
#!/bin/bash | |
# Time in seconds to wait before checking again (e.g., 60 seconds) | |
CHECK_INTERVAL=60 | |
# Maximum time in seconds without an active SSH connection before shutting down | |
MAX_IDLE_TIME=600 | |
# Path to the log file | |
LOG_FILE="/var/log/ssh_watchdog.log" | |
# Function to check for active SSH connections | |
check_ssh_connections() { | |
# Check if there are active SSH connections | |
if ss -t | grep -q ':ssh'; then | |
echo "$(date): SSH connection active." >> $LOG_FILE | |
return 0 | |
else | |
echo "$(date): No SSH connection found." >> $LOG_FILE | |
return 1 | |
fi | |
} | |
# Main loop | |
idle_time=0 | |
while true; do | |
if check_ssh_connections; then | |
# Reset idle time if there is an active connection | |
idle_time=0 | |
else | |
# Increment idle time if no active connection is found | |
idle_time=$((idle_time + CHECK_INTERVAL)) | |
fi | |
# Check if idle time exceeds the maximum allowed idle time | |
if [ "$idle_time" -ge "$MAX_IDLE_TIME" ]; then | |
echo "$(date): No SSH connections for $MAX_IDLE_TIME seconds. Shutting down." >> $LOG_FILE | |
shutdown -h now | |
exit 0 | |
fi | |
# Wait for the check interval before checking again | |
sleep $CHECK_INTERVAL | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment