Extract IP from ssh log
Extract IP from ssh log file, shown on a Debian system. Every day I see brute force attempts on my ssh, from people trying to log in. Mostly the root user, but also other usernames from popular applications. While taking very good care of my external servers, I kind of “forgot” about taking care of my home server. I have a ssh gateway at home, and the other day checking the logs I found about 90,000 attempts from the same ip for the last month. And some others attempts from the same ip block. So I just blocked the whole ip block.
Now I have a little batch script to check the logs for me, and the number of hits from each ip with failed password attempt. And extract ip. The output looks like this:
14446 183.3.202.104
15917 59.47.0.148
20244 59.47.0.152
22223 81.4.108.173
36465 183.3.202.103
The first number is the number of failed password attempts. And the the IP where the attempts come from.
This can be done from a “one liner” in bash. Here is code to extract ip from ssh logs:
count-ip.sh
#!/bin/bash
sudo grep "Failed password for" /var/log/auth.log | grep -Po "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" | sort | uniq -c | sort -n
You need to be root or sudo to read the auth.log file. It is also worth to know the auth.log file rotates every sunday morning at 06:00, at least by default on a Debian system. So the auth.log file contains all logins and logins attempts from sunday to sunday. After that it gets archives to auth.log.1 (for the first week). After that it get compressed (zipped) to auth.log.2.gz.
The code above is easy to modify to read all attempts in the compressed archive files as well. There is a similar command to grep, that is called zgrep. That will read gz files. So by modifying the code to the following, you can read the failed attempts for the last month instead of the last week. Code:sudo zgrep "Failed password for" /var/log/auth.log* | grep -Po "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" | sort | uniq -c | sort -n
Note we changed grep to zgrep and the file was changed from /var/log/auth.log to /var/log/auth.log*
So now you should be better prepared to monitor who is trying to get access to server. And who you should take action against.
Now you know how to extract ip, and if you need to know how to block ip´s read my article on ip blocking here. And see why I recommend dropping instead of rejecting connections.