扫描局域网设备 10s ping25个ip
扫描局域网设备
执行命令行程序,python多线程执行
局域网内3个设备扫描0-255 用时10s左右 单线程20分钟


苹果手机息屏时无法检测到,亮屏后初次ping会有较大延迟 约10倍 正常值(5ms)
cmd命令 ping -n 2 host
-n指定次数,默认4次浪费时间,1次可能会因为设备相应过慢遗漏
subprocess.run(['ping','-n','2',host],capture_output=True,text=True)
python运行cmd 捕捉输出 为文本形式
根据输出特点判断是否在线


设定为输出中有时间单位 ms为成功
多线程收集返回值一次返回
使用队列,每次传递该对象进入函数,函数中添加一次数据
获取队列数据直到与调用次数一致
采用装饰器的方式,由自建函数向队列添加原函数返回值
def f(queue,*args):
r=target(*args)
queue.put(r)
注意参数顺序 1.位置-2.关键字-3.默认参数-4.任意数量参数(4.1非关键字-4.2关键字)

一种有趣的参数类型 强制关键字参数 该参数只能以关键词形式提供(可以设置默认值)
获取电脑ip
电脑连接手机热点,一段时间后会变网段 但后缀不变 如 192.168.76.206变为192.168.125.206
根据这个规则提取IP
result = subprocess.run('ipconfig | findstr "192.168"', shell=True, capture_output=True, text=True)
ip=re.findall('192\.168\.\d+\.252',result.stdout)[0]
使用了管道符号、通配符等 shell 特性,要设置 shell=True
不使用管道符也行
result = subprocess.run('ipconfig ', capture_output=True, text=True)
ip=re.findall('192\.168\.\d+\.252',result.stdout)[0]
完整代码
import re
import subprocess
import threading,time
from queue import Queue
def cal(f):
# 函数运行计时
from functools import wraps
@wraps(f)
def func(*a, **b):
s = time.time()
ret = f(*a, **b)
print('{} 耗时:{}'.format(f.__name__, time.time()-s))
return ret
return func
def full_thread(target,argsM):
# 满速运行
print('任务数:{}'.format(len(argsM)))
ret=[]
queue=Queue()
def f(queue,*args):
r=target(*args)
queue.put(r)
for args in argsM:
t=threading.Thread(target=f,args=(queue,*args ))
t.start()
cnt=0
while True :
if cnt>=len(argsM):
break
if queue.empty():
time.sleep(1)
continue
r=queue.get()
ret.append(r)
cnt+=1
return ret
@cal
def scan_ip(network):
ip_pattern=network+'.{}'
args=[(ip_pattern.format(i),) for i in range(0,255) ]
result=full_thread(target=ping_host,argsM=args)
filter_result=[i[1] for i in result if i[0]]
print('获取结果数:{}'.format(len(filter_result)))
for i in filter_result:
print(i)
def ping_host(host ):
a=subprocess.run(['ping','-n','2',host],capture_output=True,text=True)
if 'ms' in a.stdout:
return [True,host]
return[False,host]
def myip():
result = subprocess.run('ipconfig ', capture_output=True, text=True)
ip=re.findall('192\.168\.\d+\.252',result.stdout)[0]
return ip
ip=myip()
print('当前ip ',ip)
newtoek=ip[:ip.rfind('.')]
scan_ip(newtoek)

浙公网安备 33010602011771号