前一陣花了點時間學習python,近段時間完成了一個監控服務器基本信息的項目,都是為了滿足大家監控的欲望,特殊日志并報警的分布式系統,單臺服務器采集粒度為1次/1分鐘,一天大約1440條,目前監控了20多臺服務器,一天大約31680條日志,現在單點監控中心服務器在性能上還綽綽有余,有更多的服務器來測試就好了,估計可以支持到100臺以上服務器監控的級別。
現在遇到一個需求是發現報警時實時發送消息給相關人員,由于公司短信網關只買了上海電信用戶沒有上海電信的號碼,汗一個,只好通過發郵件來實施。
支持發送GB18030編碼的文本內容,任意編碼附件,可以做出適當修改支持群發。
·········10········20········30········40········50········60········70········80········90········100·······110·······120·······130·······140·······150
-
-
- import os
- import sys
- from smtplib import SMTP
- from email.MIMEMultipart import MIMEMultipart
- from email.mime.application import MIMEApplication
- from email.MIMEText import MIMEText
- from email.MIMEBase import MIMEBase
- from email import Utils,Encoders
- import mimetypes
- import time
-
- STMP_SERVER = "mail.×××.com"
- STMP_PORT = "25"
- USERNAME = "×××@×××.com"
- USERPASSWORD = "×××"
- FROM = "MonitorCenterWarning@×××.com"
- TO = "×××@gmail.com"
-
- def sendFildByMail(config):
- print 'Preparing...'
- message = MIMEMultipart( )
- message['from'] = config['from']
- message['to'] = config['to']
- message['Reply-To'] = config['from']
- message['Subject'] = config['subject']
- message['Date'] = time.ctime(time.time())
- message['X-Priority'] = '3'
- message['X-MSMail-Priority'] = 'Normal'
- message['X-Mailer'] = 'Microsoft Outlook Express 6.00.2900.2180'
- message['X-MimeOLE'] = 'Produced By Microsoft MimeOLE V6.00.2900.2180'
-
- if 'file' in config:
-
- f=open(config['file'], 'rb')
- file = MIMEApplication(f.read())
- f.close()
- file.add_header('Content-Disposition', 'attachment', filename= os.path.basename(config['file']))
- message.attach(file)
-
- if 'content' in config:
-
- f=open(config['content'], 'rb')
- f.seek(0)
- content = f.read()
- body = MIMEText(content, 'base64', 'gb2312')
- message.attach(body)
-
- print 'OKay'
- print 'Logging...'
- smtp = SMTP(config['server'], config['port'])
-
- smtp.login(config['username'], config['password'])
- print 'OK'
-
- print 'Sending...',
- smtp.sendmail (config['from'], [config['from'], config['to']], message.as_string())
- print 'OK'
- smtp.close()
- time.sleep(1)
-
- if __name__ == "__main__":
- if len(sys.argv) < 2:
- print 'Usage: python %s contentfilename' % os.path.basename(sys.argv[0])
- print 'OR Usage: python %s contentfilename attachfilename' % os.path.basename(sys.argv[0])
- wait=raw_input("quit.")
- sys.exit(-1)
- elif len(sys.argv) == 2:
- sendFildByMail({
- 'from': FROM,
- 'to': TO,
- 'subject': '[MonitorCenter]Send Msg %s' % sys.argv[1],
- 'content': sys.argv[1],
- 'server': STMP_SERVER,
- 'port': STMP_PORT,
- 'username': USERNAME,
- 'password': USERPASSWORD})
- elif len(sys.argv) == 3:
- sendFildByMail({
- 'from': FROM,
- 'to': TO,
- 'subject': '[MonitorCenter]Send Msg and File %s %s' % (sys.argv[1], sys.argv[2]),
- 'content': sys.argv[1],
- 'file': sys.argv[2],
- 'server': STMP_SERVER,
- 'port': STMP_PORT,
- 'username': USERNAME,
- 'password': USERPASSWORD})
- wait=raw_input("end.")
windows xp下:

linux ubuntu,suse下:

收到的結果:
