用python监控restful接口是否正常,有异常则发送email邮件。
放在crontab中周期性检查。
例子:
 
#!/usr/bin/python
#
# www.jb200.com
import smtplib,email,sys    
from email.Message import Message    
import json  
import urllib2  
import httplib    
  
#define email info    
smtpserver='smtp.126.com'    
smtpuser='xxxx@126.com'    
smtppass='xxxxx'    
smtpport='25'    
to='xx@xx.com'
subj='ispider data bi interface Alert' 
class MyEmail:    
  def __init__(self):  
    #"connect to smtp server and return a smtplib.SMTP instance object"    
    self.server=smtplib.SMTP(smtpserver,smtpport)    
    self.server.ehlo()    
    self.server.login(smtpuser,smtppass)    
  
  def sendmessage(self,to,subj,content):    
    msg = Message()    
    msg['Mime-Version']='1.0'    
    msg['From']    = smtpuser    
    msg['To']      = to    
    msg['Subject'] = subj    
    msg['Date']    = email.Utils.formatdate()#curr datetime, rfc2822    
    msg.set_payload(content)    
    try:  
      failed =self.server.sendmail(smtpuser,to,str(msg))# may also raise exc    
    except Exception ,ex:    
      print Exception,ex    
      print 'Error - send failed'    
    else:    
      print "send success!"    
  def send(self,content):  
    self.sendmessage(to,subj,content)  
  
if __name__=="__main__":    
       
try:  
 urllib2.urlopen('http://xx:8081/itemlist')  
    
except Exception,ex:  
  print Exception,ex  
  msg=str(Exception)+'n'+str(ex)  
  print msg  
  mymail=MyEmail()  
  mymail.send(msg)  
else:  
  print 'it works well'