Python multi-thread ping a large number of servers online, python online
You need to ping the online status of all machines in a CIDR block. The shell takes too long to run. Use python to write a multi-thread ping command. The Code is as follows:
#! /Usr/bin/python # coding = UTF-8 ''' Created on 2015-8-4 @ author: Administrator ''' import threading, subprocessfrom time import ctime, sleep, timeimport Queuequeue = Queue. queue () class ThreadUrl (threading. thread): def _ init _ (self, queue): threading. thread. _ init _ (self) self. queue = queue def run (self): while True: host = self. queue. get () ret = subprocess. call ('Ping-c 1-w 1' + host, shell = True, stdout = open ('/dev/null', 'w') if ret: print "% s is down" % host else: print "% s is up" % host self. queue. task_done () def main (): for I in range (100): t = ThreadUrl (queue) t. setDaemon (True) t. start () for host in B: queue. put (host) queue. join () a = [] with open('ip.txt ') as f: for line in f. readlines ():. append (line. split () [0]) # print AB = ['2017. 168. 3. '+ str (x) for x in range (1,254)] # ping 192.168.3 network segment start = time () main () print "Elasped Time: % s" % (time () -start) # t2 = threading. thread (target = move, args = ('fff',) # threads. append (t2) ''' for I in a: print ctime () ping (I) sleep (1) if _ name _ = '_ main __': for t in range (len (a): # t. setDaemon (True) threads [t]. start () # t. join () print "All over % s" % ctime ()'''
The effect is as follows:
It only takes about seconds for a single CIDR block to be pinged. It's fast enough !!!