zabbix --python 腳本URL 監控

#!/usr/bin/python

# -*- coding: utf-8 -*-

import urllib2

import os

import sys

import logging

from time import ctime,sleep

import threading

# 設置訪問超時時間

timeout = 2

# 設置url 以字典格式存放

url={

"hcs-cloud-zuul":"http://10.41.1.132:8086/info",

"hcs-cloud-admin":"http://10.41.1.132:8089",

scriptpwd = os.path.split(os.path.realpath(sys.argv[0]))[0]

scriptname = os.path.split(os.path.realpath(sys.argv[0]))[1]

# 定義日誌路徑和名稱

log_pwd = "%s/log" %(scriptpwd)

log_pwd_name = "%s/log/%s.log" % (scriptpwd, scriptname)

def judge_file_dir(filename):

    """

    : param filename: 目錄或文件名

    : return: 存在爲 True  不存在未 False

    """

    fdresult = os.path.exists(str(filename))

    if fdresult == False:

        logging.error("目錄或者文件不存在:%s" %(filename))

    return fdresult

# 日誌文件判斷

if judge_file_dir(log_pwd) == False:

    os.mkdir(log_pwd)

fdresultlog = judge_file_dir(log_pwd_name)

if fdresultlog == False:

    newf = open(log_pwd_name,'w')

    newf.write("自動創建日誌文件'\n'")

    newf.close()

# 定義日誌

logging.basicConfig(level=logging.INFO,

                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',

                datefmt='%a, %d %b %Y %H:%M:%S',

                filename= log_pwd_name,

                filemode='a')

def determineuser():

    """

    判斷當前用戶是否爲root,若是自動退出

    : param

    : return

    """

    uid = os.geteuid()

    if uid == 0:

        logging.error("The currently executing user to root, automatic withdrawal")

        sys.exit(1)

# 訪問結果處理函數

def show_status(url,time,ip):

    req = urllib2.Request(url)

    try:

        response = urllib2.urlopen(req, timeout=time)

        status_code = response.getcode()

        if status_code != 200:

            logging.error("%s 訪問異常, 返回狀態碼爲: %s" %(url,status_code))

            threadLock.acquire()        

            iplist.append(ip)

            threadLock.release()

        response.close()

        return 0

    except Exception,e:

        logging.error("%s 訪問異常, 異常原因: %s" %(url,e))

        threadLock.acquire()

        iplist.append(ip)

        threadLock.release()

        return 1

if __name__== "__main__":

    #print "開始時間:%s" %ctime()

    iplist = []

    threadLock = threading.Lock()

    threads = []

    for i in url.keys():

        thread = threading.Thread(target=show_status,args=(url[i],timeout,i))

        threads.append(thread)

    for t in threads:

        t.setDaemon(True)

        t.start()

    t.join()

    sleep(timeout + 0.8)

    if len(iplist) == 0:

        print "訪問正常"

        #print 0

    else:

        #print 1

        print "訪問異常ip有 %s" %(" ".join(iplist)) 

    #print "結束時間:%s" %ctime()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章