Quick python script to search for IPs and get country code
This is a short script that uses a regex expression to grab IP formatted strings from a file, look up the IP in Python’s GeoIP and give back the country code. This is useful for blocking people from the usual suspect countries who always seem to be trying to hack your server or if you’re just curious about the locations of a list of IP addresses.
I put 3 different regular expressions in the script so you switch them out to better search auth.log or access.log files.
It should be noted that this is for use on Ubuntu or Debian linux systems. You may have to tweak the file and change the file paths to get it to work on other systems. It also assumes you’re using this script for auth.log and Apache access.log files.
It’s not exactly perfect, bit here it is:
#!/usr/bin/python
#import regex and Geographic IP libs
import re
import GeoIP
import sys
# give the script 1 arg if you want to scan a different file - access.log.1 for instance.
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
filename = '/var/log/apache2/access.log'
#
# Use this pattern to scan your auth.log file for logins and get the IP. If you use this change match_obj.group(1)
# to match_obj.group(2)
#
#pattern = r'(?:(.*Accepted\spassword\sfor\s){1}).*(\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b)'
# Use this pattern to scan you apache access log for POST and get the IP
#pattern = r'(\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b).*(?:(.*POST\s){1}).*'
#This gives you the IP and country
pattern = r'(\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b)'
#compile the regex
compile_obj = re.compile(pattern)
#open the file (auth/access/etc)
file2read = open(filename, 'r')
#new GeoIP cache
gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
#for all the lines in the file
for currentline in file2read:
#search them for the pattern
match_obj = compile_obj.search(currentline)
#If we get a match
if match_obj:
#set addy to matched ip - change this to 2 if you use the pattern above to find Accepted password string
addy = match_obj.group(1)
#set cc to country code based on ip
cc = gi.country_code_by_addr(addy)
#if we have coutry code, print it along with ip
if(cc):
print(addy + " " + cc )
#otherwise just print the IP
else:
print(addy)
#close the opened file
file2read.close()