1. 程式人生 > >利用python獲取nginx服務的ip以及流量統計信息

利用python獲取nginx服務的ip以及流量統計信息

服務 open contex int bin line define pytho repeat

#!/usr/bin/python
#coding=utf8

log_file = "/usr/local/nginx/logs/access.log"

with open(log_file) as f:
    contexts = f.readlines()

# define ip dict###
ip = {}     # key為ip信息,value為ip數量(若重復則只增加數量)
flow = {}   # key為ip信息,value為流量總和
sum = 0

for line in contexts:
    # count row size of flow
    size = line.split()[9]
    # print ip
    ip_attr = line.split()[0]
    # count total size of flow
    sum = int(size) + sum
    if ip_attr in ip.keys():   # if ip repeated,如果ip重復就將ip數量加一,而流量繼續疊加
	# count of ip plus 1
        ip[ip_attr] = ip[ip_attr] + 1
	# size of flow plus size
        flow[ip_attr] = flow[ip_attr] + int(size)
    else:
	# if ip not repeated 
	# define initial values of count of ip and size of flow
        ip[ip_attr] = 1
        flow[ip_attr] = int(size)

print(ip)
print(flow)
print(sum/1024/1024) 

  

利用python獲取nginx服務的ip以及流量統計信息