[1666757 views]

[]

Odi's astoundingly incomplete notes

New entries | Code

Kill idle TTYs

Here is a simple shell script to kill terminals that have been idle for a long time. You can identify such sessions in the IDLE column of the Linux w command. This corresponds to the last modified date of the respective TTY device file.
$ w
 10:56:54 up 10 days, 23:54,  7 users,  load average: 1.17, 1.10, 1.16
USER     TTY        LOGIN@   IDLE   JCPU   PCPU WHAT
aron     pts/0     10:56    1.00s  0.01s  0.01s w
betty    pts/4      Mi10   22:25m  0.02s  0.00s tail -F error.log
cher     pts/5     06:32    4:16m  0.04s  0.04s -bash
dave     pts/8     09:56   41:02   0.06s  0.05s vim config
erin     pts/9     08:26    2:26m  0.03s  0.03s -bash
fritz    pts/12    09:30    1:25m  0.03s  0.02s git server
greg     pts/13    10:47    9:26   0.32s  0.32s less +F -S --follow-name /var/log/messages

kill-idle:
#!/bin/bash
# Sends SIGHUP to TTYs which are idle for a defined time.
# Default is 8 hours. 
# Syntax: kill-idle [idle-hours]
LIMIT=${1:-8}
T=$(mktemp)
NOW=$(stat -t "${T}" | awk '{ print $12}')
[ -z ${NOW} ] && exit 1
cd /dev
for TTY in pts/*; do
  if [ "${TTY}" = "pts/ptmx" ]; then
    continue
  fi
  # field 12 is "last access" which is the time of last write to the tty (last keypress)
  MOD=$(stat -t "${TTY}" | awk '{ print $12}')
  let AGO=$((NOW - MOD))
  if [ ${AGO} -gt $((LIMIT*3600)) ]; then
    pkill -HUP -t "${TTY}"
  fi
done
rm "${T}"
 

posted on 2020-06-18 11:01 UTC in Code | 0 comments | permalink