1 Star 0 Fork 0

往日的时光/server_monitor

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
check_web_stat.py 3.62 KB
一键复制 编辑 原始数据 按行查看 历史
往日的时光 提交于 2019-08-23 16:48 . 初始化
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Author : y
@License : (C) Copyright 2013-2019, HJIMI
@Contact : bj-yez-magzine@163.com
@File : check_web_stat.py
@Time : 2019-06-24 16:58
@Desc :
'''
import sys
import socket
import ssl
from urllib.parse import urlparse
import re
import logging
from optparse import OptionParser # 命令行工具模块
logging.basicConfig()
def check(url):
"""检测一个地址是否可以正常访问.正常返回true,否则返回false"""
host = ""
scheme = "http"
port = 80
r = urlparse(url)
if (r.scheme != ""):
scheme = r.scheme
dest = r.netloc.split(":")
if(len(dest) == 2):
port = int(dest[1])
else:
if(scheme == 'http'):
port = 80
elif(scheme == 'https'):
port = 443
host = dest[0]
resource = r.path
return check_webserver(host, resource, scheme, port)
def check_webserver(host, resource, schema = "http", port = 80):
#创建一个 TCP socket
s = None
if (schema == "http"):
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
elif (schema == "https"):
s = ssl.wrap_socket(socket.socket())
if not resource.startswith('/'):
resource = '/' + resource
request_string = "GET %s HTTP/1.1\r\nHost:%s\r\n\r\n" % (resource, host)
logging.debug("Attempting to connect to %s on port %s" % (host, port))
try:
# s.settimeout(1000)
s.connect((host, port))
logging.debug("Connected to %s on port %s" % (host, port))
s.send(str.encode(request_string))
#获取前100个字节
rsp = s.recv(100)
logging.debug('Received 100 bytes of HTTP response')
logging.debug('%s' % rsp)
except socket.error as e:
logging.debug("Connection to %s on port %s failed: %s" % (host, port, e))
return False
finally:
#关闭socket连接
logging.debug("Closing the connection")
s.close()
lines = rsp.splitlines() #将一个段落的字符串以行为单位分割成一个列表
# logging.debug('First line of HTTP response: %s' % lines[0])
try:
version, status, message = re.split(r'\s+', bytes.decode(lines[0]), 2)
logging.debug('Version: %s, Status: %s, Message: %s' % (version, status, message))
except ValueError:
logging.debug('Failed to split status line')
return False
if status in ['200', '301']:
logging.debug('Success - status was %s' % status)
return True
else:
logging.debug('Status was %s' % status)
return False
if __name__=='__main__':
parser = OptionParser() #构造optionparser的对象
#往optionparser对象中增加option :parser.add_option()
parser.add_option("-d", "--host", dest="host", default='localhost', help="HOST for webserver", metavar="HOST")
parser.add_option("-r", "--resource", dest="resource", default='index.html', help="RESOURCE to check", metavar="RESOURCE")
parser.add_option("-s", "--schema", dest="schema", default='http', help="SCHEMA for request", metavar="SCHEMA")
parser.add_option("-p", "--port", dest="port", type="int", default=80, help="PORT for webserver", metavar="PORT")
(options, args) = parser.parse_args() #调用optionparser的解析函数,在options中使用解析到的options,在args中使用其他的位置参数args
# logging.debug('options: %s, args: %s' % (options, args))
# result = check_webserver(options.host, options.resource, options.schema, options.port)
result = check(args[0])
logging.debug('check_webserver returned %s' % result)
sys.exit(not result)
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/olddays/server_monitor.git
git@gitee.com:olddays/server_monitor.git
olddays
server_monitor
server_monitor
master

搜索帮助