Python multi-thread ping a large number of servers online, python online

Source: Internet
Author: User

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 !!!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.