Counting IP’s on system logs with Python

This is an example script on how to count IP’s on any log.

from collections import defaultdict
import re
import sys

d= defaultdict(int)

try:
    with open(sys.argv[1], 'r') as f:
        for row in f:
            ip=re.findall("((?:[0-9]{1,3}\.){3}[0-9]{1,3})", row)
            for i in ip:
                d[i] += 1
except IOError as error:
    print(error)

for key, value in sorted(d.items(), key=lambda x: x[1], reverse=True):
    print('IP: %s COUNT: %s' % (key,value))

This should be run like : python count_ip.py /path/to/log and the output will be like:

IP: 50.62.23.56 – COUNT: 63
IP: 189.61.20.200 – COUNT: 54
IP: 213.149.33.78 – COUNT: 45

This entry was posted in Misc and tagged , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*