Skip to content

Instantly share code, notes, and snippets.

@aqzlpm11
Last active July 26, 2017 13:12
Show Gist options
  • Save aqzlpm11/6b155073a2d8f8ca8fd81405123bc45b to your computer and use it in GitHub Desktop.
Save aqzlpm11/6b155073a2d8f8ca8fd81405123bc45b to your computer and use it in GitHub Desktop.
python: explore available ips in the LAN
# coding=utf-8
import os
from multiprocessing.dummy import Pool
def can_ping(ip):
ret = os.system('ping -n 1 -w 1 %s > nul' % ip)
can_ping = True if ret == 0 else False
return can_ping, ip
# can_ping('192.168.10.210')
# can_ping('192.168.10.211')
def ping_all():
ips = ['192.168.10.' + str(i) for i in range(1, 255)]
reachable_cnt = 0
with Pool(8) as pool:
for res, ip in pool.imap(can_ping, ips):
if res:
print(ip)
reachable_cnt += 1
print(reachable_cnt)
def ping_monitor():
ips = ['192.168.10.' + str(i) for i in range(1, 255)]
online_ips = {}
def ping_success(ip):
if ip not in online_ips:
print('found', ip)
online_ips[ip] = 2
def ping_fail(ip):
if ip in online_ips:
online_ips[ip] -= 1
if online_ips[ip] <= 0:
print('miss', ip)
del online_ips[ip]
def scan_ips(pool):
for res, ip in pool.imap(can_ping, ips):
if res:
ping_success(ip)
else:
ping_fail(ip)
with Pool(128) as pool:
while True:
scan_ips(pool)
print('.')
ping_monitor()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment