使用模块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 '完成'
~
批量测试脚本
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。