Skip to content

Instantly share code, notes, and snippets.

@shwang
Created November 5, 2015 06:25
Show Gist options
  • Save shwang/88839c0029b15c9287a9 to your computer and use it in GitHub Desktop.
Save shwang/88839c0029b15c9287a9 to your computer and use it in GitHub Desktop.
kick day-old ssh connections
#!/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