Skip to content

Instantly share code, notes, and snippets.

@pimiento
Created March 19, 2014 07:41
Show Gist options
  • Save pimiento/9637130 to your computer and use it in GitHub Desktop.
Save pimiento/9637130 to your computer and use it in GitHub Desktop.
Поиск IP-адреса, который больше всего делал запросов к серверу, согласно access.log
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import os
import sys
import fileinput
"""
Ищет наиболее активный IP-адрес в логах.
"""
def findmostIP(log):
ip_dict = {}
for line in log:
# we assume that logline looks like an "ip time ..."
ip = line.split(" ")[0]
if ip_dict.get(ip) is None:
ip_dict[ip] = 1
else:
ip_dict[ip] += 1
max_ip = max(ip_dict, key=ip_dict.get)
return "%s: %d" % (max_ip, ip_dict[max_ip])
if __name__ == "__main__":
# read from stdin or from a file
if len(sys.argv) > 1 and "-" in sys.argv[1]:
print(findmostIP(fileinput.input()))
elif len(sys.argv) > 1:
if os.path.isfile(sys.argv[1]):
print(findmostIP(open(sys.argv[1]).readlines()))
else:
exit("%s is not a file" % sys.argv[1])
else:
exit("Use \"-\" as an argument to read from stdin or filename to read from it.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment