DeaD_EyE

count_ips_nginx

Mar 16th, 2017
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.79 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. from collections import Counter
  4. import gzip
  5. import glob
  6. import sys
  7. from os.path import join
  8.  
  9. def get_ips(file):
  10.     if file.endswith('.gz'):
  11.         opener = gzip.open
  12.     else:
  13.         opener = open
  14.     with opener(file, 'rt') as fd:
  15.         text = fd.read()
  16.     return Counter(line.split()[0] for line in text.splitlines())
  17.  
  18. def all_ips(pattern):
  19.     counter = Counter()
  20.     for file in glob.glob(pattern):
  21.         counter += get_ips(file)
  22.     return counter
  23.  
  24. if __name__ == '__main__':
  25.     if len(sys.argv) != 2:
  26.         print(sys.argv[0], "'access-log-pattern'")
  27.         sys.exit(1)
  28.     counter = all_ips(join('/var/log/nginx/', sys.argv[1]))
  29.     fmt = 'IP: {:40s} N: {}'
  30.     for ip, n in counter.most_common(10):
  31.         print(fmt.format(ip, n))
Add Comment
Please, Sign In to add comment