欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Python3 实现简单的 ping 监视器并发送警报电子邮件

最编程 2024-06-21 11:30:38
...
# -*- coding:utf-8 -*-
 
__author__    =  'babyshen'
__version__   =  '0.0.3'
__datetime__  =  '2016-12-30 03:30:00'
 
import  os
import  subprocess
import  smtplib
import  sys
from  email.mime.multipart  import  MIMEMultipart
from  email.mime.base  import  MIMEBase
from  email.mime.text  import  MIMEText
from  email.utils  import  COMMASPACE,formatdate
from  email  import  encoders
 
# server['name'], server['user'], server['passwd']
def  send_mail(server, fro, to, subject = " ", text=" ", files = []):
     assert  type (server)  = =  dict
     assert  type (to)  = =  list
     assert  type (files)  = =  list
 
     msg  =  MIMEMultipart()
     msg[ 'From' =  fro                 # 邮件的发件人
     msg[ 'Subject' =  subject          # 邮件的主题
     msg[ 'To' =  COMMASPACE.join(to)   # COMMASPACE==', ' 收件人可以是多个,to是一个列表
     msg[ 'Date' =  formatdate(localtime = True # 发送时间
     msg.attach(MIMEText(text, 'plain' , 'utf-8' ))
 
     for  file  in  files:           # 添加附件可以是多个,files是一个列表,可以为空
         part  =  MIMEBase( 'application' 'octet-stream' #'octet-stream': binary data
         with  open ( file , 'rb' ) as f:
             part.set_payload(f.read())
         encoders.encode_base64(part)
         part.add_header( 'Content-Disposition' 'attachment; filename="%s"'  %  os.path.basename( file ))
         msg.attach(part)
 
     smtp  =  smtplib.SMTP()
     smtp.connect(server[ 'name' ])  # connect有两个参数,第一个为邮件服务器,第二个为端口,默认是25
     smtp.login(server[ 'user' ], server[ 'passwd' ])  # 用户名,密码
     smtp.sendmail(fro, to, msg.as_string())  # 发件人,收件人,发送信息
     smtp.close()   # 关闭连接
 
def  ping_test(src,dest):
     ping  =  subprocess.Popen( '/bin/ping -i 0.2 -c 4 -q -I '  +  src  +  ' '  +  dest,
                             shell =

上一篇: XX和OO(南阳oj1159)

下一篇: 如何在内核中编译驱动程序或模块

推荐阅读