#!/usr/bin/env python
#-*- coding:utf:8 -*-
import requests,sys,os,time
# 判断传值数知否匹配
if len(sys.argv) == 3:pass
else:
print ‘Usage: %s <monitoring_name> <interval_time>‘%(sys.argv[0])
sys.exit(2)
url = ‘url地址‘
# 覆盖存放检测值文件
def successful_state():
current = int(time.time())
interval = current + int(sys.argv[2])
file = open(‘/tmp/check_http_status_%s.txt‘%sys.argv[1],‘w‘)
file.write(str(current)+‘|‘+str(interval)+‘|‘+‘0\n‘)
file.close()
# 判断是否为json数据
def status_json():
r = requests.get(url)
status = r.status_code
try:
r.json()
print ‘OK: The current return status %s, Data as JSON format.‘%status
except:
file = open(‘/tmp/check_http_status_%s.txt‘%sys.argv[1],‘r‘)
read_file = file.read()
file.close()
read_file_three = read_file.split(‘|‘)[2]
read_file_three = int(read_file_three) + 1
if read_file_three > 3:
successful_state()
print ‘OK: The current return status %s, Data as JSON format.‘%status
else:
current = int(time.time())
interval = current + int(sys.argv[2])
file = open(‘/tmp/check_http_status_%s.txt‘%sys.argv[1],‘w‘)
file.write(str(current)+‘|‘+str(interval)+‘|‘+str(read_file_three))
file.close()
print ‘WARNING: The current return status %s, The data is not a JSON format.‘%status
sys.exit(1)
# 获取链接状态码进行判断
def check_status():
# 用异常处理来判断url是否可正常访问(没有链接返回码),超时时间为4秒
try:
r = requests.get(url, timeout=4)
except:
print ‘ERROR: Unable to display this page.‘
sys.exit(2)
status = r.status_code
# 如果链接不等于200 先判断检测错误次数是否连续超过3次 如果超过三次则停止返回错误状态 否则返回错误状态
if status != 200:
current = int(time.time())
interval = current + int(sys.argv[2])
file = open(‘/tmp/check_http_status_%s.txt‘%sys.argv[1],‘r‘)
read_file = file.read()
file.close()
read_file_three = read_file.split(‘|‘)[2]
read_file_three = int(read_file_three) + 1
if read_file_three > 3:
successful_state()
status_json()
else:
print ‘ERROR: The current return status %s.‘%status
file = open(‘/tmp/check_http_status_%s.txt‘%sys.argv[1],‘w‘)
file.write(str(current)+‘|‘+str(interval)+‘|‘+str(read_file_three))
file.close()
sys.exit(2)
else:
status_json()
# 检测文件是否存在 如果存在 则判断当前时间是否大于指定的时间 如果大于 则正常检测 否则告知间隔时间
def interval():
current = int(time.time())
interval = current + int(sys.argv[2])
file_path = os.path.exists(r‘/tmp/check_http_status_%s.txt‘%sys.argv[1])
if file_path == True:
file = open(‘/tmp/check_http_status_%s.txt‘%sys.argv[1],‘r‘)
read_file = file.read()
file.close()
read_file_two_value = int(read_file.split(‘|‘)[1])
if current >= read_file_two_value:
check_status()
successful_state()
else:
print ‘From the next execution interval and %s seconds.‘%(read_file_two_value - current)
else:
filename = open(‘/tmp/check_http_status_%s.txt‘%sys.argv[1],‘w‘)
filename.write(str(current)+‘|‘+str(current)+‘|‘+‘0\n‘)
filename.close()
print ‘Run for the first time, will in the next run to get the data.‘
interval()
本文出自 “、矿泉水” 博客,请务必保留此出处http://guwenqiang.blog.51cto.com/5462040/1709356
Python定时返回网址状态码&&网页内容是否为json数据
原文地址:http://guwenqiang.blog.51cto.com/5462040/1709356