ping包,包含名字以及ip地址的实现,一个小程序:
可以实现设备的名称以及对应IP的地址的检测,便于查看设备信息,了解哪些在线,哪些不在线。
import os
from ping3 import ping
import csv
import time
import os
import sys
from concurrent.futures import ThreadPoolExecutor as pool
#核心原理是:concurrent.futures会以子进程的形式,平行的运行多个python解释器,
# 从而令python程序可以利用多核CPU来提升执行速度。由于子进程与主解释器相分离,
# 所以他们的全局解释器锁也是相互独立的。每个子进程都能够完整的使用一个CPU内核。
# 读取csv文件
def readcsvfile(filename="./config/ipaddr.csv"):
if not os.path.exists(filename):
print("ipaddr.csv文件不存在,请配置检测的IP地址!")
sys.exit()
with open(filename,'r')as fr:
swaplines = []
csvreader=csv.reader(fr)
for line in csvreader:
if line[0]=='ip':
continue
# print(line)
# print(line[0])
swaplines.append(line)
return swaplines
# pinginfo(line)
def pinginfo(ipline):
pingretlist=[] # 添加一个临时变量列表,pingretlist
# flag=-1
ip=ipline[0]
ipname=ipline[1]
ping_result=ping(ip)
if ping_result==None:
flag='x'
typleswap = [ip, ipname, flag]
# writecsvfile(typleswap)
pingretlist.append(typleswap)
else:
flag = '√'
typleswap = [ip, ipname, flag]
# writecsvfile(typleswap)
pingretlist.append(typleswap) # 添加一个临时变量列表,pingretlist
writecsvfile(pingretlist)
def writecsvfile(rows):
# row = ['192.168.1.9', 'xx路口', ‘√’]
# 写入数据,newline=" "是为了避免写入之后有空行
with open('./destdata/result.csv','a+',newline='')as f:
fcsv=csv.writer(f) # readee 自己的文件
# fcsv.writerow(header) # 单行写入
fcsv.writerows(rows)
if __name__ == '__main__':
# start = time.time()
print(" 2021-10-20...")
print("IP 状态检测,请稍等...")
print("==="*18)
listall=readcsvfile() #获取所有的检测的IP的地址和名称信息的列表。
with pool(max_workers=10)as t: #多线程的调用
for ipline in listall:
task=t.submit(pinginfo,ipline)
print("检测完成,请在程序的destdata/result.csv文件下获取结果!")
time.sleep(100)
# end = time.time()
# print("持续运行时间为:{}".format(end - start))



