作者:AD社团 | 来源:互联网 | 2017-05-13 02:18
#!/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"&#43;"<"&#43;mail['mail_user']&#43;"@"&#43;mail['mail_postfix']&#43;">"
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
以上就介绍了python脚本监控nginx服务,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。