WEB服務器巡檢腳本

腳本功能:html

監控多臺Web服務器狀態,一旦發生問題就發送郵件python


運行環境:linux

Python2.7/2.4皆可運行web


腳本使用方法:服務器

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

*/10 * * * * 腳本路徑ide


腳本運行效果以下:
url


腳本內容以下:spa

#!/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 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 = '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 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不爲空,就說明服務器有問題,那就發送郵件

    if problem_server_list:

        send_mail(''.join(problem_server_list))

相關文章
相關標籤/搜索