This article mainly introduces the use of Python to implement network testing methods, the text gives a detailed sample code for everyone to reference the study, for everyone has a certain reference learning value, the need for friends below to see it together.
Objective
Recently, my classmates asked me to help write a test network tool. As a result of the work, it took a long time to give a relatively complete version. In fact, I use less python, so the basic is to check the data side write program.
The main logic of the program is as follows:
Read the list of IPs in an Excel file, then use multi-threaded calls to ping to count the network parameters for each IP, and finally output the results to an Excel file.
The code looks like this:
#! /usr/bin/env python#-*-coding:utf-8-*-# file:pingtest_test.py# date:2008-09-28# author:michael Field# Modified by:i ntheworld# date:2017-4-17import sysimport osimport getoptimport commandsimport subprocessimport reimport timeimport Threadingimport xlrdimport xlwttest = [' 220.181.57.217 ', ' 166.111.8.28 ', ' 202.114.0.242 ', ' 202.117.0.20 ', ' 202.112.2 6.34 ', ' 202.203.128.33 ', ' 202.115.64.33 ', ' 202.201.48.2 ', ' 202.114.0.242 ', ' 202.116.160.33 ', ' 202.202.128.33 ',]resul T={}def usage (): print "useage:" print "\t%s-n test|excel name [-t times of Ping] [-C Concurrent Number (thread Nums)]"%s Ys.argv[0] print "\ t test is the IP list of the simple test" print "\t-t times, the default is" print "\t-c concurrent number Parallel threads: The default is" print "\ t-h|-?, Help Information "print" \ t output as current directory file Ping_result.txt and Ping_result.xls "print" For example: "Print" \t./ping_test.py-n test- T 1-c "def p_list (ls,n): If not isinstance (ls,list) or not isinstance (n,int): return [] Ls_len = Len (ls) print ' ls len gth =%s '%ls_len if n<=0 or 0==ls_len:return [] if n > ls_len:return [] elif n = = Ls_len:return [[i] for i in ls] else:j = ls_len/n K = ls_len%n # # J,j,j,... (preceded by N-1 J), J+k #步长j, number of n-1 Ls_return = [] for i in xrange (0, (n-1) *j,j): Ls_return.append (Ls[i:i+j]) #算上末尾的j +k Ls_ret Urn.append (ls[(n-1) *j:]) return ls_returndef pin (IP): Try:xpin=subprocess.check_output ("Ping-n 1-w%s"%ip, Shell =true) except Exception:xpin = ' empty ' ms = ' =[0-9]+ms '. Decode ("UTF8") print "%s"%ms print "%s"%xpin Mstime=re.search ( Ms,xpin) If not mstime:ms= ' timeout ' return MS else:ms=mstime.group (). Split (' = ') [1] return Ms.strip (' MS ') def count (to Tal_count,i): global RESULT nowsecond = Int (Time.time ()) nums = 0 Oknums = 0 Timeout = 0 Lostpacket = 0.0 Total_ms = 0.0 A Vgms = 0.0 MAXMS = 1 while nums < total_count:nums + = 1 MS = Pin (I) print ' pin output =%s '%MS if MS = = ' Timeout ': timeout + = 1 Lostpacket = timeout*100.0/nums Else:oknums + = 1 Total_ms = Total_ms + float (ms) if Oknums = = 0:oknums = 1 Maxms = float (MS) avgms = total_ms/oknums Else:avgms = total_ms/oknums Maxms = ma X (Maxms, float (MS)) result[i] = (I, Avgms, Maxms, Lostpacket) def thread_func (T, IPList): If not isinstance (iplist,list): Return else:for IP in iplist:count (t, IP) def readipsinfile (excelname): data = Xlrd.open_workbook (excelname) Table = Data.sheets () [0] nrows = table.nrows print ' nrows%s '%nrows ips = [] for I in range (nrows): Ips.append (Table.cell_value ( I, 0)) print table.cell_value (i, 0) return ips if Name = = ' Main ': File = ' ping_result.txt ' times = Ten Network = ' thread _num = Ten args = sys.argv[1:] Try: (opts, getopts) = getopt.getopt (args, ' n:t:c:h? ') except:print "\ninvalid command li NE option detected. " Usage () sys.exit (1) for OPT, Arg in opts:if opt in ('-n '): Network = arg if opt in ('-h ', '-? '): Usage () Sys.exi T (0) if opt in ('-t '): times = Int (arg) if opt in ('-C '): thread_num = int (arg) f = open (file, ' W ') workbook = xlwt. WoRkbook () Sheet1 = Workbook.add_sheet ("Sheet1", cell_overwrite_ok=true) if not isinstance (times,int): Usage () sys.exit (0 If network not in [' TEST '] and not os.path.exists (Os.path.join (os.path.dirname (file), network)): print "The network is Wrong or Excel file does not exist. Please check it. " Usage () sys.exit (0) else:if Network = = ' Test ': ips = Test else:ips = readipsinfile (Network) print ' Starting ... ' Threads = [] Nest_list = P_list (IPs, thread_num) loops = Range (len (nest_list)) print ' Total%s threads is working ... ' %len (nest_list) for iplist in nest_list:t = Threading. Thread (target=thread_func,args= (times,iplist)) Threads.append (t) for I in Loops:threads[i].start () for I in loops: Threads[i].join () it = 0 for line in Result:value = Result[line] Sheet1.write (it, 0, line) sheet1.write (it, 1, STR ('%.2f '%value[1]) sheet1.write (it, 2, str ('%.2f '%value[2])) Sheet1.write (it, 3, str ('%.2f '%value[3])) It+=1 F. Write (line + ' \ t ' + str ('%.2f '%valuE[1]) + ' \ t ' + str ('%.2f '%value[2]) + ' \ t ' + str ('%.2f '%value[3]) + ' \ n ') f.close () workbook.save (' Ping_result.xls ') prin T ' work done. Please check result%s and Ping_result.xls. ' %file
This code refers to the implementation of others, although not particularly complex, here is a simple explanation.
Excel reads and writes using XLRD and XLWT, basically using a few simple APIs.
Multithreading is implemented using the threading, which is very similar to the POSIX standard interface. Thread_func is a thread handler function whose input contains a list of IPs, so the individual IPs are processed inside the function by looping through them.
In addition, Python's commands is not compatible under Windows, so the Subprocess module is used.
So far, my understanding of the Python character set is not in place, so the regular expression matching code is not strong enough, but now reluctantly work, it is necessary to change it later!
Summarize