一、原理:
多线程调用系统Ping命令
主要涉及的系统命令: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}.') |
本机测试环境下执行时间2-3s左右
其它应用场景:群Ping本机号段,快速建立arp关系表,再结合arp做一些其它的事情。