tcpdump+python编写的流量监控的脚本

由于公司的员工有的上网老爱下东西,所以自己编写了的一个流量监控脚本,如果谁的流量过大就会发邮件给管理员。只适用于本公司。首先用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')

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值