====== 服务器状态监控脚本 ======
作者:屈伟 (http://quwei.techweb.com.cn) 转载请注明来源
===== 通用:发送邮件=====
使用mail.139.com免费邮箱,发邮件到139邮箱是能免费把邮件内容发到手机上,从而时间实时手机报警
#!/usr/bin/env python
import os
##author:Qu Wei(http://quwei.techweb.com.cn)
gtalk = "kenvinqu@gmail.com"
mobile = "Moble No"
import smtplib
from email.mime.text import MIMEText
to_addr = 'qu-wei@139.com'
mailserver = 'smtp.139.com'
username = mobile+'@139.com'
password = 'xxxx'
from_addr = mobile+'@139.com'
def sendmail(subject, body) :
msg = MIMEText(body)
msg['Subject'] = subject
svr = smtplib.SMTP(mailserver)
#svr.set_debuglevel(1) #print debug
svr.login(username,password)
svr.sendmail(from_addr,to_addr,msg.as_string())
svr.close()
===== 检查磁盘 =====
#!/usr/bin/env python
import os
import re
import urllib
df = os.popen("df -kh").readlines()
#print df
i = 0
for line in df:
item = re.split("\s+", line)
i = i +1
if i < 2 or i > 4: continue;
if len(item) < 5 : continue;
##print "item:", item
p = int( item[4].replace("%","") )
if p > 90 :
msg = "Disk is full ! "+ line
sendmail('disk', msg)
===== ping服务器 =====
import re
import os
plists = ['x.x.x.x', 'x.x.x.x']]
def ping(ip) :
cmd = "ping -c 5 %s" % ip
print cmd
c = os.popen(cmd).read()
m = re.search("(\d+) packets transmitted, (\d+) received", c)
i = int( m.group(2) )
print i
if i < 2 :
##ping第二次,防止误判
cmd = "ping -c 5 %s" % ip
print cmd
c = os.popen(cmd).read()
m = re.search("(\d+) packets transmitted, (\d+) received", c)
i = int( m.group(2) )
if i < 2 :
msg = "IP:%s ping error, received:%s" % (ip, i)
sendmail('ping', msg)
for ip in plists :
ping(ip)
===== 检查从库运行状态 =====
import re
import os
##author:Qu Wei(http://quwei.techweb.com.cn)
MYSQL_SH = "/usr/local/mysql/bin/mysql "
def check_slave(name, sh) :
msg = ""
str = os.popen(MYSQL_SH + sh + " -e 'show slave status\G'").read()
##print "str::", str
if not str:
msg = name + ": mysql error, cannot connect ";
sendmail('mysql', msg)
return
p = re.compile("Slave_IO_Running:\s+(\w+)", re.M)
m = p.search(str)
if m:
if "Yes" != m.group(1):
msg = ": Slave_IO_Running:" + m.group(1)
if msg :
msg = name + ": mysql slave error, " + msg
sendmail('mysql', msg)
else:
print "MySql: ", name, " OK!";
check_slave("66 3306 slave", "-uuser -ppwd -P3306 -h211.100.42.x");