python脚本监控nginx服务

#!/usr/local/bin/python
#coding:UTF-8

import socket
import smtplib
import urllib
import os
import sys
import time
from email.mime.text import MIMEText

#email options
mail_options = {
'mail_host':'smtp.xxx.com',
'mail_user':'xxx@xxx.com',
'mail_pass':'xxxxxx',
'mail_postfix':'xxx.com',
'mail_toList':['xxx@xxx.com'],
}


#server url
host_url = "xxxxxx"


#check nginx server status
def check_nginx():
for i in range(3):
time.sleep(3)
try:
result = os.popen('ps -C nginx -o pid,cmd').readlines()
if len(result) < 2:
print "nginx process killed, restarting service in 3 seconds."
time.sleep(3)
os.system('/usr/local/nginx/sbin/nginx')
else:
break;
except:
print "Error!"




#check server status
def url_request(url):
try:
response = urllib.urlopen(url);
response_code = response.getcode()
if 500 == response_code:
return response_code
elif 501 == response_code:
return response_code
elif 502 == response_code:
return response_code
elif 503 == response_code:
return response_code
elif 504 == response_code:
return response_code
else:
return True
except IOError,e:
return False


#restart cas service
def cas_restart():
try:
print "cas restarting service in 3 seconds."
time.sleep(3)
os.system('xxx')
return True
except:
print "Error"
return False


#send email
def send_mail(mail,sub,content):
    me="server monitor"+"<"+mail['mail_user']+"@"+mail['mail_postfix']+">"
    msg = MIMEText(content,_subtype='plain')
    msg['Subject'] = sub
    msg['From'] = me
    msg['To'] = ";".join(mail['mail_toList'])                
    try:
        server = smtplib.SMTP()
        server.connect(mail['mail_host'])                            
        server.login(mail['mail_user'],mail['mail_pass'])               
        server.sendmail(me, mail['mail_toList'], msg.as_string())
        server.close()
        return True
    except Exception, e:
        print str(e)
        return False


if __name__=='__main__':
check_nginx()
status = url_request(host_url)
if status is not True and status is not None:
restart_result = cas_restart()
if restart_result is True:
content = "Server:%s was died! status code:%s.\r\nThe service restarts successfully."%(host_url, status) 
send_mail(mail_options, "monitor", content)
else:
content = "Server:%s was died! status code:%s.\r\nThe service failed to restart, please restart the service again."%(host_url, status) 
send_mail(mail_options, "monitor", content)
else:
pass
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值