指令碼功能:
監控多台Web伺服器狀態,一旦發生問題就發送郵件
運行環境:
Python2.7/2.4皆可運行
指令碼使用方法:
可利用Crontab或者計劃任務來指定時間運行,例如:
*/10 * * * * 指令碼路徑
指令碼運行效果如下:
650) this.width=650;" src="http://img1.51cto.com/attachment/201306/132120320.png" title="QQ20130605132048.png" />
指令碼內容如下:
#!/usr/bin/env python# coding=utf-8#----------------------------------------------------------# Name: WEB伺服器巡檢指令碼# Purpose: 監控多台Web伺服器狀態,一旦出現問題就發送郵件# Version: 1.0# Author: LEO# BLOG: http://linux5588.blog.51cto.com# EMAIL: chanyipiaomiao@163.com# Created: 2013-06-04# Copyright: (c) LEO 2013# Python: 2.4/2.7#----------------------------------------------------------from smtplib import SMTPfrom email import MIMETextfrom email import Headerfrom datetime import datetimeimport httplib#定義要檢測的伺服器,URL 連接埠號碼 資源名稱web_servers = [('192.168.1.254', 80, 'index.html'), ('www.xxx.com', 80, 'index.html'), ('114.114.114.114', 9000, '/main/login.html'), ]#定義主機 帳號 密碼 收件者 郵件主題smtpserver = 'smtp.163.com'sender = 'xxxx@xxx.com'password = 'password'receiver = ('收件者1','收件者2')subject = u'WEB伺服器警示郵件'From = u'Web伺服器'To = u'伺服器管理員'#定義記錄檔位置error_log = '/tmp/web_server_status.txt'def send_mail(context): '''發送郵件''' #定義郵件的頭部資訊 header = Header.Header msg = MIMEText.MIMEText(context,'plain','utf-8') msg['From'] = header(From) msg['To'] = header(To) msg['Subject'] = header(subject + '\n') #串連SMTP伺服器,然後發送資訊 smtp = SMTP(smtpserver) smtp.login(sender, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.close()def get_now_date_time(): '''擷取當前的日期''' now = datetime.now() return str(now.year) + "-" + str(now.month) + "-" \ + str(now.day) + " " + str(now.hour) + ":" \ + str(now.minute) + ":" + str(now.second)def check_webserver(host, port, resource): '''檢測WEB伺服器狀態''' if not resource.startswith('/'): resource = '/' + resource try: try : connection = httplib.HTTPConnection(host, port) connection.request('GET', resource) response = connection.getresponse() status = response.status content_length = response.length except : return False finally : connection.close() if status in [200,301] and content_length != 0: return True else: return Falseif __name__ == '__main__': logfile = open(error_log,'a') problem_server_list = [] for host in web_servers: host_url = host[0] check = check_webserver(host_url, host[1], host[2]) if not check: temp_string = 'The Server [%s] may appear problem at %s\n' % (host_url,get_now_date_time()) print >> logfile, temp_string problem_server_list.append(temp_string) logfile.close() #如果problem_server_list不為空白,就說明伺服器有問題,那就發送郵件 if problem_server_list: send_mail(''.join(problem_server_list))
本文出自 “雷納科斯的部落格” 部落格,請務必保留此出處http://linux5588.blog.51cto.com/65280/1216417