#!/usr/bin/python
python
# -*- coding: utf-8 -*-app
import urllib2
ide
import os
函數
import sys
ui
import logging
url
from time import ctime,sleep
spa
import threading
日誌
# 設置訪問超時時間
code
timeout = 2
orm
# 設置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()