简单的利用python调用ansible检测内网服务器磁盘,然后报警,看代码吧,写得有点糙,很多地方都没有考虑异常抛出,和处理,暂时能用就行,The following code:
#!/usr/bin/env python # encoding: utf-8 #Author: Lucky chen import datetime,time,traceback import smtplib,os,re import threading from string import join def sendmail(subject='', msg='', fromaddr='lucky@hadoope.com', toaddrs=): from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart mail_msg = MIMEMultipart() mail_msg['Subject'] = subject mail_msg['From'] = fromaddr mail_msg['To'] = ','.join(toaddrs) mail_msg.attach(MIMEText(msg, 'html', 'utf-8')) #print mail_msg.as_string() try: ### Intranet mail server s = smtplib.SMTP('10.3.8.2') s.sendmail(fromaddr, toaddrs, mail_msg.as_string()) s.quit() except: error_result = traceback.format_exc() print error_result def check_sendmail(zn,hn): #The recipient email mailto_list=['ronghua@139.com', 'lucky@hadoope.com'] f = '%' mail_content = "host %s %s zone used gt 95%s" % (hn, zn, f) sub = "online host Disk usage" sendmail(subject=sub, msg=mail_content, toaddrs=mailto_list) def check_result(cmd,hname): resu = os.popen(cmd).read().strip().split() #print resu #To obtain / /data zone Pointer to the location rnum, dnum = resu.index("/") - 1 , resu.index("/data") - 1 ## get root /data zone % num rzone, dzone = int(resu[rnum].split('%')[0]), int(resu[dnum].split('%')[0]) #print type(rzone) #print rzone,dzone,hname if rzone > 95: check_sendmail(zn="/",hn=hname) if dzone > 95: check_sendmail(zn='/data',hn=hname) if __name__=='__main__': ##ansible host list /etc/ansible/hosts host=['web1','web2','db1','db2'] for dest in host: comm = "ansible %s -m shell -a 'df -h'" % (dest) #print comm #check_result(cmd=comm,hname=dest) s = threading.Thread(target = check_result,args = (comm,dest)) s.start()