Created
November 5, 2015 06:25
-
-
Save shwang/88839c0029b15c9287a9 to your computer and use it in GitHub Desktop.
kick day-old ssh connections
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 | |
# kick_idle_ssh.sh | |
# Hangs up ssh connections that have been idle for over a day. | |
# | |
# AUTHOR: shwang 2015.11.4 | |
MAX_IDLE_TIME=86400 | |
# `who` only displays login sessions (thus excluding tmux/screen sessions). | |
# It's pretty safe to assume that on bastions, all sessions listed by `who` | |
# are ssh connections. | |
who | tr -s ' ' | while read entry; do | |
user=$(echo $entry | cut -d' ' -f1) | |
tty=$(echo $entry | cut -d' ' -f2) | |
((idletime = "$(date "+%s")" - "$(stat --format="%X" "/dev/${tty}")" )) | |
if ((idletime > MAX_IDLE_TIME)); then | |
pid=$(ps -u "$user" | grep -i "$tty" | head -1 | tr -s ' ' | cut -d' ' -f1) | |
echo 'You exceeded idle time of 24 hours.' | write $user $tty | |
kill -HUP $pid # hangup the ssh connection | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment