标签:python
我们可以通过在网关上添加iptables规则来监控某台主机的上传或下载流量,以下是具体步骤:
添加iptables规则:
/sbin/iptables -I INPUT -s 10.0.5.110
创建数据库进行存储:只需一列,
mysql> desc proxy; +-------+----------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+----------+------+-----+---------+-------+ | ip | char(20) | YES | | NULL | | +-------+----------+------+-----+---------+-------+ 1 row in set (0.00 sec)
使用Python获取流量,并做判断:
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import subprocess import MySQLdb import smtplib from email.mime.text import MIMEText import sys reload(sys) sys.setdefaultencoding(‘utf-8‘) def get_traffic(): j = subprocess.Popen("/sbin/iptables -n -v -x -L INPUT|grep all|grep 10.0.5", shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) u = j.communicate() n = u[0].split(‘\n‘) return n def html_construct(): con = MySQLdb.connect(host=‘localhost‘,user=‘user‘,passwd=‘passwd‘,db=‘traffic_monitor‘,charset=‘utf8‘) cur = con.cursor() html = "" html_head = """ <html> <body> <font size="3"><b>流量监控:</b></h3><br></br><br></br> <table align="center"> <table border="1px" marginleft="20px" cellspacing="0" bordercolor="#336699" width="800"> <tr bgcolor="#99ccff" height="20px"> <th style="color:#336699">ip</th> <th style="color:#336699">姓名</th> <th style="color:#336699">流量</th> </tr> """ html += html_head #两列进行相减,得出增量 sql = ‘select proxy.ip, name.name, proxy.a%s - proxy.a%s as s from proxy, name where proxy.ip = name.ip‘ % (x, y) cur.execute(sql) for data in cur.fetchall(): if int(data[2]) > int(‘%s‘ % (z)): global content_flag content_flag = 1 html_content = ‘<tr><td>%s</td><td>%s</td><td>%sM</td></tr>‘ % (data[0], data[1], data[2]) html += html_content html_tail = """ </table> </table> </body> </html> """ html += html_tail return html cur.close() def send_mail(SUBJECT): TO = ‘itd@lightchaseranimation.com‘ msg = MIMEText(content, ‘html‘, ‘utf-8‘) msg[‘Subject‘] = SUBJECT msg[‘From‘] = FROM msg[‘To‘] = TO mail = smtplib.SMTP(‘localhost‘) mail.sendmail(FROM, TO, msg.as_string()) if __name__=="__main__": #定义三个时间:当前时间,半小时前,一个小时前 time1 = datetime.datetime.now() time2 = time1 - datetime.timedelta(minutes=30) time3 = time1 - datetime.timedelta(minutes=60) now = time1.strftime(‘%Y%m%d%H%M‘) ago = time2.strftime(‘%Y%m%d%H%M‘) old = time3.strftime(‘%Y%m%d%H%M‘) content_flag = 0 con = MySQLdb.connect(host=‘localhost‘,user=‘user‘,passwd=‘passwd‘,db=‘traffic_monitor‘,charset=‘utf8‘) cur = con.cursor() #增加一列:列名为a+当前时间 #删除一列:列名为a+一个小时前 cur.execute(‘alter table proxy add column a%s int(10) default %s‘ % (now, 0)) if str(time3.weekday()) != "0" or old[-4:] != "0005": cur.execute(‘alter table proxy drop column a%s‘ % (old)) #插入数据 traffic_return = get_traffic() for line in traffic_return: data = line.split() if len(data) > 0: sql = ‘update proxy set a%s = "%s" where ip = "%s"‘ % (now, int(data[1])/1048576, data[6]) cur.execute(sql) cur.close() #每半小时执行一次,流量增加超过150M,报警 x = now y = ago z = 150 content = html_construct() if content_flag == 1: FROM = ‘proxy_traffic@lightchaseranimation.com‘ SUBJECT = ‘【监控】上传流量‘ send_mail(SUBJECT) #每周进行一次汇总,流量增加超过300M,报警 if str(time1.weekday()) == "0" and now[-4:] == "0005": time4 = time1 - datetime.timedelta(days=7) last = time4.strftime(‘%Y%m%d%H%M‘) x = now y = last z = 300 content = html_construct() FROM = ‘proxy_traffic_weekly@lightchaseranimation.com‘ SUBJECT = ‘【监控】上传流量周报告‘ send_mail(SUBJECT)
创建crontab
本文出自 “11062687” 博客,请务必保留此出处http://11072687.blog.51cto.com/11062687/1768071
标签:python
原文地址:http://11072687.blog.51cto.com/11062687/1768071