[python] 트래픽 초과 시 메일 발송하기

Python 2016.12.01 11:24 Posted by 김한별 behonestar

트래픽 한계치, GMail 계정과 비밀번호를 설정해야 한다.


#!/usr/bin/env python from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.header import Header from email import Encoders from urllib2 import urlopen import time import math import smtplib MAIL_SEND_INTERVAL = 3600 #sec INTERVAL = 1 #sec WARN_KBPS = 212234 #kbps PUB_IP = urlopen('http://ip.42.pl/raw').read()


ignore = 0 prev_bytes = -1 rate_history = [] def GetNetworkInterfaces(): f = open("/proc/net/dev") data = f.read() f.close() data = data.split("\n")[2:] for i in data: i = i.replace(':', ' ') if len(i.strip()) > 0: x = i.split() k = { "interface" : x[0][:len( x[0])-1], "tx" : { "bytes" : int(x[1]), "packets" : int(x[2]), "errs" : int(x[3]), "drop" : int(x[4]), "fifo" : int(x[5]), "frame" : int(x[6]), "compressed" : int(x[7]), "multicast" : int(x[8]) }, "rx" : { "bytes" : int(x[9]), "packets" : int(x[10]), "errs" : int(x[11]), "drop" : int(x[12]), "fifo" : int(x[13]), } } if k["interface"] == "eth": return k return None def send_email(to, bitrate): gmail_username="yourname" gmail_user="user@yourdomain.com" gmail_pwd="***********" msg=MIMEMultipart('alternative') msg['From']=gmail_username msg['To']=to msg['Subject']=Header("RELAY SERVER [%s] TRAFFIC WARNING!" % PUB_IP,'utf-8') msg.attach(MIMEText("Average Rates: %d kbps" % bitrate, 'plain', 'utf-8')) mailServer=smtplib.SMTP("smtp.gmail.com",587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(gmail_user,gmail_pwd) mailServer.sendmail(gmail_user, to, msg.as_string()) mailServer.close() print "send email [%s]" % to while True: idata = GetNetworkInterfaces() if prev_bytes == -1: prev_bytes = idata["rx"]["bytes"] continue cur_rate = (idata["rx"]["bytes"] - prev_bytes) / INTERVAL prev_bytes = idata["rx"]["bytes"] if len(rate_history) > 10: rate_history.pop(0) rate_history.append(cur_rate) sum_rate = 0 for rate in rate_history: sum_rate += rate avg_rate = sum_rate / len(rate_history) avg_rate = avg_rate*8/1024 print "CUR: %d kbps AVG: %d kpbs" % (cur_rate*8/1024, avg_rate) if avg_rate > WARN_KBPS: ignore -= 1 if ignore < 0: send_email("user@yourdomain.com", avg_rate) ignore = MAIL_SEND_INTERVAL #1hour  

    time.sleep(INTERVAL)