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)

    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:

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 /path/to/log and the output will be like:

IP: – COUNT: 63
IP: – COUNT: 54
IP: – 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 *