Skip to content

Commit 89efae8

Browse files
committed
find-inactive-ssh-sessions.sh handle situation without TTYs
1 parent 2d6862e commit 89efae8

File tree

1 file changed

+19
-10
lines changed

1 file changed

+19
-10
lines changed

bin/find-inactive-ssh-sessions.sh

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,24 @@ while getopts ":hksi:" opt; do
5151
esac
5252
done
5353

54+
# Get TTYs with the seconds since the last access time
55+
TTYS=$(
56+
who -s \
57+
| awk '{ print $2 }' \
58+
| grep -ve "^:"
59+
)
60+
if [ "$TTYS" = "" ]; then
61+
echo "Suitable TTYs not found; no SSH sessions to find." >&2
62+
exit 0
63+
fi
64+
65+
TTY_AGES=$(
66+
echo "$TTYS" \
67+
| (cd /dev && xargs stat -c '%U %n %X') \
68+
| awk '{ print $1"\t"$2"\t"'"$(date +%s)"'-$3 }'
69+
)
70+
71+
# Print header
5472
if (( KILL == 1 )); then
5573
echo "Killing sshd processes idle more than $MAX_IDLE seconds." >&2
5674
else
@@ -63,16 +81,7 @@ else
6381
fi
6482
echo "" >&2
6583

66-
# Get TTYs with the seconds since the last access time
67-
TTY_AGES=$(
68-
who -s \
69-
| awk '{ print $2 }' \
70-
| grep -ve "^:" \
71-
| (cd /dev && xargs stat -c '%U %n %X') \
72-
| awk '{ print $1"\t"$2"\t"'"$(date +%s)"'-$3 }'
73-
)
74-
75-
# Get sshd processes of the TTYs; print or kill (-k)
84+
# Get sshd processes of the TTYs; list or kill (-k)
7685
while IFS= read -r line ; do
7786
user=$(echo "$line" | awk '{print $1}')
7887
tty=$(echo "$line" | awk '{print $2}')

0 commit comments

Comments
 (0)