Skip to content

Instantly share code, notes, and snippets.

@JonathanWillitts
Created May 12, 2022 12:57
Show Gist options
  • Save JonathanWillitts/0ef027bc0b378130c0c45ab6734e0cf4 to your computer and use it in GitHub Desktop.
Save JonathanWillitts/0ef027bc0b378130c0c45ab6734e0cf4 to your computer and use it in GitHub Desktop.
Show the last (accepted, via SSH Key) connection by user
#!/bin/bash
#####
# Shows the last (accepted, via SSH Key) connection for each user.
#
# How? By searching all auth logs (inc gzipped ones), and filtering to show
# most recent accepted connections
#
# Works/tested on: Ubuntu 18.04.6 LTS (bionic)
#
# Usage: [sudo] last_ssh_login.sh
#
###############################################################################
find /var/log -name auth.log\* -print0 \
| xargs -0 zgrep --no-filename "Accepted publickey for" \
| sort -k1Mr -k2nr -k3r \
| awk '{ printf "%s %02i %s %s\n", $1,$2,$3,$9 }' \
| awk '!seen[$4]++'
# Command explained: https://explainshell.com/explain?cmd=sudo+find+%2Fvar%2Flog+-name+auth.log%5C*+-print0+%7C+xargs+-0+zgrep+--no-filename+%22Accepted+publickey+for%22+%7C+sort+-k1Mr+-k2nr+-k3r+%7C+awk+%27%7B+printf+%22%25s+%2502i+%25s+%25s%5Cn%22%2C+%241%2C%242%2C%243%2C%249+%7D%27+%7C+awk+%27%21seen%5B%244%5D%2B%2B%27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment