思路:通过http判断网络通断,通过ping获取网络的状态

注意:不同平台下,调用的系统命令返回格式可能不同,跨平台使用的时候,注意调整字符串截取的值

主程序:network_testing_v0.3.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019-04-19 09:50
# @Author : yuyongxr
# @Site :
# @File : network_testing_v0.1.py
# @Software: PyCharm
# from icmp_test import *
from http_test import *
from config import *
import threading
import time
import json http_status = True def start_check_http(url,title):
global http_status
while True:
if check_http(url,title):
http_status = True
# print("http_status :", http_status)
else:
http_status = False
print("http_status :", http_status)
file = open("http_logs.txt", "a")
file.write(time.asctime(time.localtime(time.time()))+ " : http status is " +str(http_status) + "\n")
time.sleep(1) def check_continuous():
url,title,ip_address,times,domain,dnsserver = analyze_config()
t_http = threading.Thread(target=start_check_http,args=(url,title))
t_http.start() def icmp_continuous(): global http_status
global avg_list
global lost_list avg_list = []
lost_list = []
url,title,ip_address,times,domain,dnsserver = analyze_config() while True:
if http_status:
min, avg, max, lost = "","","",""
try:
min, avg, max, lost = shend_icmp_packet(ip_address, times) avg_flag = 0
avg_list.append(float(avg)) for a in avg_list:
avg_flag = avg_flag + a
avg_flag = avg_flag/len(avg_list) lost_flag = 0
lost_list.append(float(lost))
for a in lost_list:
lost_flag = lost_flag + a
lost_flag = lost_flag / len(lost_list) file = open("result.json")
content = file.read()
file.close()
content = json.loads(content)
content["ping"]["min"] =float(content["ping"]["min"]) if float(content["ping"]["min"]) <= float(min) else min
content["ping"]["avg"] = avg_flag
content["ping"]["max"] = float(content["ping"]["max"]) if float(content["ping"]["max"]) >= float(max) else max
content["ping"]["lost"] = lost_flag
content = json.dumps(content) file = open("result.json","w")
file.write(content)
file.close() print(min, avg, max, lost)
except:
pass
else:
time.sleep(1)
continue
time.sleep(5) def main():
c_check = threading.Thread(target=check_continuous)
i_icmp = threading.Thread(target=icmp_continuous) c_check.start()
i_icmp.start() if __name__ == '__main__':
main()

主程序

获取网络状态:icmp_test.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019-04-19 18:08
# @Author : yuyongxr
# @Site :
# @File : icmp_test.py
# @Software: PyCharm
import os def shend_icmp_packet(ip_address,times):
try:
response = os.popen('ping -c ' + times + ' '+ ip_address).read()
# 取出丢包率
lost = response[response.index("%")-4:response.index("%")]
#取出指定的延时字符串
res = list(response)
index = 0
count = 0
for r in res:
count += 1
if r == "=" :
index = count
response = response[index + 1:-4] # 取出执行的延迟
i = 0
j = []
res1 = list(response)
for r in res1:
i += 1
if r == "/" :
j.append(i) min = response[:j[0]-1]
avg = response[j[0]:j[1]-1]
max = response[j[1]:j[2]-1]
return min,avg,max,lost
except :
print("ping exec error")
file = open("icmp_logs.txt","a")
file.write(time.asctime(time.localtime(time.time())) +" ping exec error \n")

获取网络状态

判断网络通断:http_test.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019-04-19 18:09
# @Author : yuyongxr
# @Site :
# @File : http_test.py
# @Software: PyCharm import requests,bs4,time
from requests.exceptions import ReadTimeout,ConnectTimeout,HTTPError,ConnectionError def send_http_packet(url):
requests.packages.urllib3.disable_warnings()
user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"
headers = {'User-Agent': user_agent}
url = "http://" + url
response_html= ""
file = open("http_logs.txt","a")
try:
response = requests.get(url, headers)
response_html = response.content.decode()
return response_html
except ReadTimeout:
print('Read Timeout')
file.write(time.asctime(time.localtime(time.time())) + " Read Timeout \n")
file.close()
return False
except ConnectTimeout:
print('Connect Timeout')
file.write(time.asctime(time.localtime(time.time())) + " Connect Timeout \n")
file.close()
return False
except HTTPError:
print('HTTP Error')
file.write(time.asctime(time.localtime(time.time())) + " HTTP Error \n")
file.close()
return False
except ConnectionError:
print('Connection Error')
file.write(time.asctime(time.localtime(time.time())) + " Connection Error \n")
file.close()
return False def check_http(url,title):
html = send_http_packet(url)
file = open("http_logs.txt","a")
if html != False and title != False :
soup = bs4.BeautifulSoup(html, 'lxml')
html_title = ""
html_title = soup.title.text
if title in html_title:
return True
else:
return False
else:
print('html or title is None')
file.write(time.asctime(time.localtime(time.time())) + " html or title is None \n")
file.close()
return False

判断网络通断

配置文件:config.json

{
"dns":{"domain":"www.baidu.com","dnsserver":"114.114.114.114"},
"icmp":{"ip_address":"www.baidu.com","times":""},
"http":{"url":"www.baidu.com","title":"百度"}
}

配置文件

解析配置文件:config.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019-04-19 18:28
# @Author : yuyongxr
# @Site :
# @File : config.py
# @Software: PyCharm import json def read_config():
file = open("config.json")
content = file.read()
file.close()
return content def analyze_config():
config = read_config()
config = json.loads(config) url = config["http"]["url"]
title = config["http"]["title"] ip_address = config["icmp"]["ip_address"]
times = config["icmp"]["times"] domain = config["dns"]["domain"]
dnsserver = config["dns"]["dnsserver"] return url,title,ip_address,times,domain,dnsserver

解析配置文件

结果存储文件:result.json

{"ping": {"min": 46.828, "avg": 137.0165, "max": 150.587, "lost": 0.7446808510638298}}

结果存放

python 判断网络通断同时检测网络的状态的更多相关文章

  1. Delphi检测网络连接状态

    有时候,我们做一些小软件就需要检测网络连接状态,比如想给你的软件加上类似QQ那样的系统消息,可是像我这样的穷人肯定是买不起服务器了,那我们只好另想办法,可以读取网页然后用浏览器显示,这个时候就需要判断 ...

  2. iOS开发 - Swift实现检测网络连接状态及网络类型

    一.前言 在移动开发中,检测网络的连接状态尤其检测网络的类型尤为重要.本文将介绍在iOS开发中,如何使用Swift检测网络连接状态及网络类型(移动网络.Wifi). 二.如何实现 Reachabili ...

  3. Python获取CPU、内存使用率以及网络使用状态代码

    Python获取CPU.内存使用率以及网络使用状态代码_python_脚本之家 http://www.jb51.net/article/134714.htm

  4. [Swift通天遁地]四、网络和线程-(6)检测网络连接状态

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...

  5. iOS检测网络连接状态

    官方Demo下载地址:https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip 将Reachab ...

  6. Android 检测网络连接状态

    Android连接网络的时候,并不是每次都能连接到网络,因此在程序启动中需要对网络的状态进行判断,如果没有网络则提醒用户进行设置. 首先,要判断网络状态,需要有相应的权限,下面为权限代码(Androi ...

  7. iOS 网络与多线程--1.检测网络链接状态

    通过Reachability库,检测设备的网络连接状况. 使用到的类库:Reachability Reachability库,是一个iOS环境下,检测设备网络状态的库,可以在网络上搜索下载. 使用之前 ...

  8. android检测网络连接状态示例讲解

    网络的时候,并不是每次都能连接到网络,因此在程序启动中需要对网络的状态进行判断,如果没有网络则提醒用户进行设置   Android连接首先,要判断网络状态,需要有相应的权限,下面为权限代码(Andro ...

  9. qt检测网络连接状态【只能检测和路由器的连接,不能测试到外网的连接】

    #include <QCoreApplication>#include <QDebug>#include <QTextStream>#include <QDi ...

随机推荐

  1. git http服务免登录实现(免去每次请求用户名密码输入,Visual Studio可用)

    最近用了Bonobo搭起了Git服务,弄了个批处理文件来避免每次都要输入用户名密码. 此脚本分为三个步骤:1.添加用户变量HOME:2.添加用户_netrc文件:3.添加windows普通凭据(因为V ...

  2. C# 添加、修改以及删除Excel迷你图表的方法

    Excel表格中的迷你图表能够直观地向我们展示出数据的变化趋势.本文将介绍C#如何实现为表格数据生成迷你图表,以及修改和删除迷你图表的方法.下面将详细讲述. 所用组件工具:Spire.XLS for ...

  3. Maven(十二)Maven 依赖详解

    依赖的传递性 注意1:在Eclipise创建的Maven项目,若依赖eclipse空间中其他自己创建的 的项目时,此时并不会报错,但是当执行mvn compile命令时还是会显示缺失败.所以依赖的其他 ...

  4. C#设计模式之二十一访问者模式(Visitor Pattern)【行为型】

    一.引言 今天我们开始讲“行为型”设计模式的第九个模式,该模式是[访问者模式],英文名称是:Visitor Pattern.如果按老规矩,先从名称上来看看这个模式,我根本不能获得任何对理解该模式有用的 ...

  5. noi.ac #289. 电梯(单调队列)

    题意 题目链接 Sol 傻叉的我以为给出的\(t\)是单调递增的,然后\(100\rightarrow0\) 首先可以按\(t\)排序,那么转移方程为 \(f[i] = min_{j=0}^{i-1} ...

  6. 功能强大的PDF实用工具

    PDF实用工具(PDFTool)是北京博信施科技有限有限公司研制开发的一款专门提供对PDF文件进行编辑.加工的处理软件.本软件具有对PDF文件进行分割.结合.加密.解密.添加水印.设定有效期限等多种功 ...

  7. .net 支付宝接口小小误区

    1.该密匙目测不是私钥,应用官方文档生成的长私钥. 2. 此公钥用的是应用公钥 3.设置支付完成后的通知页面和回调页面 其他的按照官方文档的demo来实现即可

  8. Linux 环境 Maven 安装&仓源配置

    索引: 目录索引 参看代码 GitHub: maven.txt 一.Linux (DeepinOS) 环境 1.官网下载 https://maven.apache.org/download.cgi 2 ...

  9. MongoDB副本集功能及节点属性梳理

    副本集的主要功能 副本集是MongoDB高可用的基础,其主要作用 归纳为以下几点: (1)高可用,防止设备(服务器.网络)故障.提供自动FailOver功能. (2)无需配置高可用性虚拟节点:无论是S ...

  10. Session session = connection.createSession(paramA,paramB);参数解析

    Session session = connection.createSession(paramA,paramB); paramA是设置事务,paramB是设置acknowledgment mode ...