Find a Brute-Force Attack in auth.log With grep, awk and sort
Your server is on the internet, so someone is guessing SSH passwords right now. Here's how to see it, measure it and respond, using only standard tools. You can practise every command safely in the free browser lab on Co
Your server is on the internet, so someone is guessing SSH passwords right now. Here's how to see it, measure it and respond, using only standard tools. You can practise every command safely in the free browser lab on CoreQ Academy.
1. Look at the evidence
On Debian and Ubuntu, SSH authentication events go to /var/log/auth.log (on RHEL-family systems, /var/log/secure). You need root or membership in the adm group to read it.
sudo tail -n 20 /var/log/auth.log
Nov 01 02:11:04 web-01 sshd[811]: Failed password for root from 203.0.113.45 port 51122 ssh2
Nov 01 02:11:05 web-01 sshd[812]: Failed password for invalid user admin from 203.0.113.45 port 51134 ssh2
2. Count failed attempts
sudo grep -c "Failed password" /var/log/auth.log
3. Find who is attacking
Extract the source IP from each failure line, then count by IP:
sudo grep "Failed password" /var/log/auth.log \
| awk '{for (i=1; i<=NF; i++) if ($i == "from") print $(i+1)}' \
| sort | uniq -c | sort -rn | head
312 203.0.113.45
41 198.51.100.77
2 192.0.2.10
Using awk to find the word after from is more robust than a fixed column number, because "invalid user" lines have extra words.
4. Which accounts are being targeted?
sudo grep "Failed password" /var/log/auth.log \
| grep -oE "for (invalid user )?[^ ]+" | awk '{print $NF}' \
| sort | uniq -c | sort -rn | head
Lots of invalid user guesses (admin, oracle, test) mean automated scanning. Many usernames each failing once from one IP is password spraying.
5. The most important check: did anything succeed?
sudo grep "Accepted" /var/log/auth.log
A success from an IP that was just failing hundreds of times is an incident. Investigate immediately.
6. Fix the root cause
Blocking one IP helps for a minute. Removing the exposure helps for good:
# /etc/ssh/sshd_config
PermitRootLogin no
PasswordAuthentication no
sudo sshd -t && sudo systemctl reload ssh
Use key-based authentication, and consider restricting SSH to a VPN or bastion host. Make sure your own key works before disabling passwords.
Practise it
The CoreQ labs "Who is knocking? Reading the auth log" and "Find the noisiest attacker" walk through exactly this, graded automatically, in a simulated server.
I'm Sean Ofodile, a cybersecurity leader, founder of Quantum Core Services and CIO of Seenu.io, an early-stage social discovery startup. I teach free cybersecurity classes at CoreQ Academy and on YouTube as Professor Sean Ofodile, and was featured on 11Alive in Atlanta with the Seenu team.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.