首页 > 代码库 > 利用python获取nginx服务的ip以及流量统计信息

利用python获取nginx服务的ip以及流量统计信息

#!/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以及流量统计信息