ping,python实现批量ping包工具--小案例v5阶段版本,可以使用了,最近在项目上需求一个检测设备状态的工具,找寻了很多,都是不能满足自己的需求,

编写了一个ping包检测工具,可以实现,ping包中包含IP地址,IP地址名称,检测结果可以出现是否ping通的统计情况记录:

基本使用需求:

1.新建‘config’文件夹,里面包含“ipaddr.csv”文件,这个里面有两个字段“ip,ip名称”,内容类似

ip

ip名称

192.168.1.9

谷歌

223.5.5.5

test

8.8.8.8

阿里

2.“destdata”文件夹,存放生成的结果文件,“result.csv”里面有个这个文件,结果内容:

223.5.5.5

test


223.5.5.5

test


223.5.5.5

test


8.8.8.8

阿里


8.8.8.8

阿里


8.8.8.8

阿里


223.5.5.5

test


8.8.8.8

阿里


223.5.5.5

test


8.8.8.8

阿里


192.168.1.9

谷歌

x

192.168.1.9

谷歌

x

192.168.1.9

谷歌

x

192.168.1.9

谷歌

x

修改了几个版本后终于确定了这个可以投入使用。

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()

    if not os.path.exists(filename) or not os.path.exists('./config'):
        print("ipaddr.csv文件不存在,或者‘config文件夹不存在!’请检查./config/ipaddr.csv")
        sys.exit()




    with open(filename,'r')as fr:
        swaplines = []
        csvreader=csv.reader(fr)
        for line in csvreader:
            if line[0]=='ip':   # 判断是否是表头,如果是表头的话,就是跳过这一行
                continue

            if line[1]=="":   # 判断第二列是否‘’值,如果是空值的话,就是写入‘#’,符号,进行填充。
                line[1]="#"
            # print(line)
            # print(line[0])

            swaplines.append(line)

        return swaplines    # 返回一个列表,到main程序中,调用这个列表





            # pinginfo(line)


# 核心模块,检测是否在线,‘from ping3 import ping’中ping3中的ping模块进行检测。
def pinginfo(ipline):


    ip=ipline[0]
    ipname=ipline[1]
    ping_result=ping(ip)    # 调用ping3中的ping模块


    if ping_result==None:    #  如果检测不在线的话,把ip,name,flag都是写入typeswap列表中
        flag='x'
        typleswap = [ip, ipname, flag]

        # writecsvfile(typleswap)
    else:
        flag = '√'
        typleswap = [ip, ipname, flag]


    writecsvfile(typleswap)   # 调用下面的函数







def writecsvfile(row):
    # rows = ['192.168.1.9', 'xx路口', ‘√’]



    # 写入数据,newline=" "是为了避免写入之后有空行

    with open('./destdata/result.csv','a+',newline='')as f:
        fcsv=csv.writer(f)    # readee 自己的文件

        # fcsv.writerow(header)    # 单行写入
        fcsv.writerow(row)

def printjindu(response):
    """
    打印一个正在检测的状态‘#’的数量代表着进度运行情况。
    :return:
    """
    # print("#",end='')
    print("★",end='',flush=True)



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)
            task.add_done_callback(printjindu)   #这个是在多线程运行过程中,可以调用另外一个程序




    print("\n")
    print("检测完成,请在程序的destdata/result.csv文件下获取结果!")


    end = time.time()
    print("持续运行时间为:{}".format(end - start))
    time.sleep(100)