ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-10-28 17:55:05  阅读:241  来源: 互联网

标签:shell python ip ping threads import 多线程


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

suprocess 创建子进程生成多个shell


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




#!/usr/bin/python
#-*- coding: utf-8 -*- 
from threading import Thread
import subprocess
from Queue import Queue
import pymysql
num_threads=10
q=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 '完成'
~

批量测试脚本

图片.png

标签:shell,python,ip,ping,threads,import,多线程
来源: https://blog.51cto.com/lusiyuan/2446043

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有