千家信息网

python 多线程ping 2秒ping完500个ip地址

发表于:2025-02-09 作者:千家信息网编辑
千家信息网最后更新 2025年02月09日,使用模块queue 队列控制访问全局变量suprocess 创建子进程生成多个shell此脚本可用于网络割接改造时 判断各个设备的网络连通性,ip地址和设备名字均从企业配置库读取。利用队列控制变量读取
千家信息网最后更新 2025年02月09日python 多线程ping 2秒ping完500个ip地址

使用模块queue 队列控制访问全局变量

suprocess 创建子进程生成多个shell


此脚本可用于网络割接改造时 判断各个设备的网络连通性,ip地址和设备名字均从企业配置库读取。利用队列控制变量读取。2秒之内快速ping完




#!/usr/bin/python#-*- coding: utf-8 -*- from threading import Threadimport subprocessfrom Queue import Queueimport pymysqlnum_threads=10q=Queue()def pingme(i,queue):    while True:        ip=queue.get()        ret=subprocess.call('ping -c 1 %s' % ip[0],shell=True,stdout=open('/dev/null','w'),stderr=subprocess.STDOUT)        #[接受变量字符串为命令,ping发送一个ICMP请求,并且将标准输出重定向到/dev/null,相当于丢弃,并且将标准错误输出重新定向到标准输出。        这条语句返回其实就是ping值,就是python程序先创建shell进程,shell创建ping进程,ping进程运行返回值被shell等待,shell返回值给        python程序wait,如果成功则为0.]        if ret==0:              print '%s-%s is up!' %(ip[1],ip[0])        elif ret==1:            print '%s is down...'%(ip[1],ip[0])        queue.task_done()#start num_threads threads  for i in range(num_threads):    t=Thread(target=pingme,args=(i,q))#多线程调用    t.setDaemon(True) #设置守护线程    t.start()db = pymysql.connect(    host="10.50.99.247",    user="network",    passwd="xxxx",    port=3306,    db="network",    charset='utf8')cursor = db.cursor()cursor.execute("select ipadd,name from net_dev where `group` like 'xxx%' ")data = cursor.fetchall()for i in data:    q.put(i) #上传列表q.join();print '完成'~

批量测试脚本


0