Python implements fast multi-thread ping, and python multi-thread ping
This article describes how to implement fast multi-thread ping using Python. Share it with you for your reference. The details are as follows:
#! /Usr/bin/python # _ * _ coding: UTF-8 _ * _ # ''' name: Fast multithread ping program development: gyhong gyh9711 Date: 20: 51 2011-04-25 ''' import pexpectimport datetimefrom threading import Threadhost = ["192.168.1.1", "192.168.1.123", "192.168.2.1", "192.168.1.1", "192.168.1.123", "192.168.2.1 ", "192.168.1.1", "192.168.1.123", "192.168.2.1", "192.168.1.1", "192.168.1.123", "192.168.2.1 ", "192.168.1.1"] report_ OK = [] report_error = [] class PING (Thread): def _ init _ (self, ip): Thread. _ init _ (self) self. ip = ip def run (self): Curtime = datetime. datetime. now () # Scrtime = Curtime + datetime. timedelta (0, minute, 0) # print ("[% s] host [% s]" % (Curtime, self. ip) ping = pexpect. spawn ("ping-c1% s" % (self. ip) check = ping. secondary CT ([pexpect. TIMEOUT, "1 packets transmitted, 1 received, 0% packet loss"], 2) if check = 0: print ("[% s] TIMEOUT % s" % (Curtime, self. ip) elif check = 1: print ("[% s] % s reachable" % (Curtime, self. ip) else: print ("[% s] HOST % s inaccessible" % (Curtime, self. ip) # Run T_thread = [] for I in host: t = PING (I) T_thread.append (t) for I in range (len (T_thread) in multiple threads simultaneously )): t_thread [I]. start () ## print ("\ n ========= problematic hosts: ===========\ n ") # output (report_error) # print ("\ n ========= normal host information: =============\ n ") # output (report_ OK)
Execution result:
Administrator @ nagios:/win/pexpect $./ping. py
[21:30:22. 126981] 192.168.1.1 reachable
[21:30:22. 148376] 192.168.1.1 reachable
[21:30:22. 179846] 192.168.1.1 reachable
[21:30:22. 203691] 192.168.1.1 reachable
[21:30:22. 227696] 192.168.2.1 reachable
[21:30:22. 134049] timeout 192.168.1.123
[21:30:22. 145610] timeout 192.168.2.1
[21:30:22. 157558] timeout 192.168.1.123
[21:30:22. 167898] timeout 192.168.2.1
[21:30:22. 197572] timeout 192.168.1.123
[21:30:22. 202430] timeout 192.168.2.1
[21:30:22. 215561] timeout 192.168.1.123
[21:30:22. 229952] timeout 192.168.1.1
I hope this article will help you with Python programming.