AutoFramework/Base/Class/Network.py

65 lines
2.0 KiB
Python
Raw Normal View History

2022-06-30 23:56:05 +08:00
import re, chardet, platform, subprocess, socket
2022-06-27 23:11:22 +08:00
def ping(host='', version=None):
2022-06-29 23:25:57 +08:00
def shell_exec(cmd='', timeout=None):
2022-06-27 23:11:22 +08:00
try:
2022-06-28 15:13:05 +08:00
result = subprocess.run(
cmd, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=timeout)
2022-06-27 23:11:22 +08:00
if result.stdout:
return result.stdout.decode(chardet.detect(result.stdout)["encoding"] or 'UTF-8')
return ''
except:
return ''
2022-06-30 23:56:05 +08:00
2022-06-27 23:11:22 +08:00
match version:
case 4 | 6:
2022-06-29 23:25:57 +08:00
version_ch = '\x20-' + str(version)
2022-06-27 23:11:22 +08:00
case _:
2022-06-29 23:25:57 +08:00
version_ch = ''
2022-06-27 23:11:22 +08:00
match platform.system():
case 'Windows':
2022-06-29 23:25:57 +08:00
result = shell_exec('chcp 65001 && ping -n 1' + version_ch + ' ' + host, timeout=5)
2022-06-27 23:11:22 +08:00
case _:
2022-06-29 23:25:57 +08:00
result = shell_exec('ping -c 1' + version_ch + ' ' + host, timeout=5)
2022-06-30 23:56:05 +08:00
delay = re.findall('([0-9.]+)[\s]?ms*', result)
2022-06-29 23:25:57 +08:00
if len(delay) == 0:
2022-06-27 23:11:22 +08:00
return False
else:
2022-06-30 23:56:05 +08:00
return round(float(delay[0]), 1)
2022-06-27 23:11:22 +08:00
2022-06-29 23:25:57 +08:00
def resolve(host='', version=None):
result = []
lst = []
2022-06-27 23:11:22 +08:00
try:
2022-06-29 23:25:57 +08:00
lst = socket.getaddrinfo(host, None)
2022-06-27 23:11:22 +08:00
except:
2022-06-29 23:25:57 +08:00
pass
for value in lst:
address = value[4][0]
2022-06-27 23:11:22 +08:00
match value[0]:
case socket.AddressFamily.AF_INET6:
2022-06-30 23:56:05 +08:00
if version == 6 or version is None:
2022-06-29 23:25:57 +08:00
result.append(address)
2022-06-27 23:11:22 +08:00
case _:
2022-06-30 23:56:05 +08:00
if version == 4 or version is None:
2022-06-29 23:25:57 +08:00
result.append(address)
return result
2022-06-27 23:11:22 +08:00
2022-06-30 23:56:05 +08:00
2022-06-27 23:11:22 +08:00
if __name__ == '__main__':
2022-06-29 23:25:57 +08:00
# Example. PING IPv4 Test.
print('PING:', ping('www.taobao.com', version=4), 'ms')
# Example. PING IPv6 Test.
print('PING:', ping('www.taobao.com', version=6), 'ms')
# Example. PING Auto Test.
print('PING:', ping('www.taobao.com'), 'ms')
# Example. Resolve IPv4-Only Host.
print(resolve('www.taobao.com', version=4))
# Example. Resolve IPv6-Only Host.
print(resolve('www.taobao.com', version=6))
# Example. Resolve IPv4/6 Host.
print(resolve('www.taobao.com'))