由于公司的员工有的上网老爱下东西,所以自己编写了的一个流量监控脚本,如果谁的流量过大就会发邮件给管理员。只适用于本公司。首先用tcpdump抓包,然后用python的正则表达式对其进行处理。然后统计流量。刚学python,望大家指教。
tcpdump抓包的脚本
#!/bin/bash
tcpdump -i eth0 ip -nn 'src net !192.168.2.0/24 and !192.168.3.0/24 and !192.168.0.0/24' -vv >/root/tcpdump.log&
sleep 3
killall -9 tcpdump
#!/usr/bin/python
def singleipflow(dstip): 此函数用于统计单个ip在某段时间的流量
import sys
import re
import string
countflow=0
starttime=[]
q=open('/root/tcpdump.log','r')
m=q.readlines()
q.close()
for eachline in m:
if re.search('length',eachline) and re.search('IP',eachline) and re.search(dstip,eachline) is not None:
info=re.match('(/d+:/d+:/d+/./d+|).*length/s(/d+).*/)/s(/d{1,3}/./d{1,3}/./d{1,3}/./d{1,3}).*?(/d{1,3}/./d{1,3}/./d{1,3}/./d{1,3}).*',eachline)
# print info.groups()
if info.group(1)!='':
dstipinfo=info.group(4)
singleflow=info.group(2)
if dstipinfo==dstip:
countflow+=int(singleflow)
starttime.append(info.group(1))
else:
continue
sumflow=(countflow,starttime)
return sumflow
import os
import sys
import re
import string
while True:
os.system('/python/tcpdump.sh')
import time
datetime=time.time()
# print type(datetime)
timestring=time.ctime(datetime)
# print type(timestring)
print timestring
del datetime
for j in [2,3]:
for i in range (1,254,1):
dstip='192.168.'+str(j)+'.' + str(i)
m=singleipflow(dstip)
if len(m[1])<=1:
pass
elif len(m[1])>1:
begintime=re.search('(/d/d):(/d/d):(/d/d/./d{6})',m[1][0])
endtime=re.search('(/d/d):(/d/d):(/d/d/./d{6})',m[1][len(m[1])-1])
starttime=float(begintime.group(1))*60+float(begintime.group(2))*60+float(begintime.group(3))
stoptime=float(endtime.group(1))*60+float(endtime.group(2))*60+float(endtime.group(3))
time=stoptime-starttime
if time>1:
avgflow=int(m[0])/time/1024/2
print '%-15s%20s%20s%10skB/s' %(dstip,m[1][0],m[1][len(m[1])-1],str(avgflow)[:5])
if avgflow>100:
file=open('/python/text','w')
file.write(dstip)
file.close()
print '%-15s%20s%20s%10skB/s is overflow' %(dstip,m[1][0],m[1][len(m[1])-1],str(avgflow)[:5])
os.system('mail -s "ip is overflow" xxx@163.com</python/text')
else:
pass
print 'one round is over'
print ''
os.system('rm -rf /root/tcpdump.log')