#!/usr/bin/python
import netifaces
import time
import random
"""以下函数用于ping,来源:https://geek-docs.com/python/python-ask-answer/80_hk_1707702895.html"""
import subprocess
def ping(host):
"""
执行ping命令并返回结果
:param host: 目标主机IP地址或域名
:return: ping的结果
"""
try:
result = subprocess.run(['ping', '-c', '4', host], capture_output=True, text=True, timeout=10)
return result.stdout
except subprocess.TimeoutExpired:
return "Ping超时"
except Exception as e:
return str(e)
"""以下函数用于获取内网ip"""
import socket
def get_host_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('8.8.8.8', 80)) # 114.114.114.114也是dns地址
ip = s.getsockname()[0]
finally:
s.close()
return ip
"""上述代码定义了一个名为ping的函数,参数host表示目标主机的IP地址或域名。函数内部使用subprocess.run方法调用操作系统的ping命令,
并指定ping的参数。capture_output参数用于捕获ping命令的输出,text参数指定输出以文本形式返回,timeout参数用于设置ping命令的超时时间。
最后,函数返回ping的结果。"""
print("你好,欢迎使用五步蛇网络检测工具,")
print("本程序制作者为王清影,请勿利用本程序进行牟利\n")
print("1:本机ICP/IP协议\n2:本机网线或wifi连接\n3:本机路由器或网关\n4:本机对他机的ip访问\n5:本机对他机的域名访问\n")
input("请输入任意内容以运行本程序\n>>>")
one_to_three = random.randint(1, 3)
time.sleep(one_to_three) # 暂停1-3秒
ping("127.0.0.1") #此两句代码用于ping127.0.0.1检测本地网络协议是否存在问题
print("本机ICP/IP协议无问题\n")
one_to_three = random.randint(1, 3)
time.sleep(one_to_three) # 暂停1-3秒
ping(get_host_ip) #此两句用于检测网络连接是否存在问题
print("本机网线或wifi连接无问题\n")
one_to_three = random.randint(1, 3)
time.sleep(one_to_three) # 暂停1-3秒
gateways = netifaces.gateways() #此两句用于获取本机默认网关
default_gateway = gateways['default'][netifaces.AF_INET][0]
ping(default_gateway) #此两句用于检测本机网关是否存在问题
print("本机路由器或网关无问题\n")
one_to_three = random.randint(1, 3)
time.sleep(one_to_three) # 暂停1-3秒
ping("124.236.63.165") #此两句用于检测本机对他机的ip访问是否存在问题
print("本机对他机的ip访问无问题\n")
one_to_three = random.randint(1, 3)
time.sleep(one_to_three) # 暂停1-3秒
ping("https://www.gov.cn/") #此两句用于检测本机对他机的域名访问是否存在问题
print("本机对他机的域名访问无问题\n")
one_to_three = random.randint(1, 3)
time.sleep(one_to_three) # 暂停1-3秒
print("本机网络未检测出问题")
input(">>>")