天天看點

WEB伺服器巡檢腳本

腳本功能:

監控多台Web伺服器狀态,一旦發生問題就發送郵件

運作環境:

Python2.7/2.4皆可運作

腳本使用方法:

可利用Crontab或者計劃任務來指定時間運作,例如:

*/10 * * * * 腳本路徑

腳本運作效果如下:

腳本内容如下:

#!/usr/bin/env python

# coding=utf-8

#----------------------------------------------------------

# Name:         WEB伺服器巡檢腳本

# Purpose:      監控多台Web伺服器狀态,一旦出現問題就發送郵件

# Version:      1.0

# Author:       LEO

# BLOG:         http://linux5588.blog.51cto.com

# EMAIL:        [email protected]

# Created:      2013-06-04

# Copyright:    (c) LEO 2013

# Python:       2.4/2.7

from smtplib import SMTP

from email import MIMEText

from email import Header

from datetime import datetime

import 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 = '[email protected]'

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 False

if __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不為空,就說明伺服器有問題,那就發送郵件