一、原理:
主要涉及的系统命令:ping -n 1 -w 1 IP地址
-n 为ping的次数,在linux下为-c;-w为等待超时时间;
利用Python多线程缩短时间,提升运行效率。
二、其它说明
DEV_NULL = open(os.devnull, 'w') 是在Python中实现的黑洞,类似linux的/dev/null, 将subprocess.call的标准输出和标准错误重定向到黑洞,只接受返回状态码,不在终端显示执行结果。
三、运行环境
Python版本:≥ 3.10
可操作平台:Linux、Windows(mac没有试过)
使用方法:命令行下执行 python netping.py 192.168.1 (只接受掩码24的网段)
netping.py代码如下:
import os
import sys
import platform
import threading
import subprocess
PLANT = platform.system()
DEV_NULL = open(os.devnull, 'w')
PING_RESULT = []
match PLANT:
case 'Windows':
PING_ARGS = ['ping', '-n', '1', '-w', '1']
case _:
PING_ARGS = ['ping', '-c', '1', '-w', '1']
def single_ping(subnet, host):
ip_addr = f'{subnet}{host}'
status_code = subprocess.call(
args=PING_ARGS + [ip_addr],
stdout=DEV_NULL,
stderr=DEV_NULL
)
if status_code == 0:
PING_RESULT.append(host)
def group_ping(sub):
ping_threads = []
for i in range(1, 255):
t = threading.Thread(target=single_ping, args=[sub, i])
t.start()
ping_threads.append(t)
for pt in ping_threads:
pt.join()
def show_result(sub):
new_result = sorted(PING_RESULT)
for i in new_result:
print(f'{sub}{i}')
print(f'\nPing: {len(new_result)} Pong.')
def main(sub):
group_ping(sub)
show_result(sub)
DEV_NULL.close()
if __name__ == '__main__':
subnet = sys.argv[1]
if subnet[-1] == '.':
main(subnet)
else:
main(f'{subnet}.')
如果您有改善或指正意见,欢迎交流,可在评论区回复,或者发送邮件至<[email protected]>!!
标签:subnet,sub,批量,Python,PING,ping,DEV,result From: https://www.cnblogs.com/jialehao/p/16968826.html