Share web test scripts using Python and share scripts using python
Preface
Recently, I was asked to help write a tool to test the network. It took a long time to get a relatively complete version due to work issues. In fact, I use less Python, so I usually query data and write programs.
The main logic of the program is as follows:
Read the ip address list in an excel file, use multiple threads to call ping to count the network parameters of each ip address, and output the result to the excel file.
The Code is as follows:
#! /Usr/bin/env python #-*-coding: UTF-8-*-# File: pingtest_test.py # Date: 2008-09-28 # Author: Michael Field # Modified By: intheworld # Date: 2017-4-17import sysimport osimport getoptimport commandsimport subprocessimport reimport timeimport threadingimport xlrdimport xlwtTEST = ['2017. 181.57.217 ', '2017. 111.8.28 ', '2017. 114.0.242 ', '2017. 117.0.20 ', '2017. 112.26.34 ', '2017. 203.128.33 ', '2017. 115.64.33 ', '2 02.201.48.2 ', '2017. 114.0.242 ', '2017. 116.160.33 ', '2017. 202.128.33 ',] RESULT = {} def usage (): print "USEAGE: "print" \ t % s-n TEST | excel name [-t times of ping] [-c concurrent number (thread nums)] "% sys. argv [0] print "\ t TEST is the IP address list for simple testing" print "\ t-t times TEST times. The default value is 1000; "print" \ t-c concurrent number of parallel threads: The default value is 10 "print" \ t-h | -?, The help information "print" \ t is output to the current directory file ping_result.txt and ping_result.xls "print" for example: "print" \ t. /ping_test.py-n TEST-t 1-c 10 "def div_list (ls, n): if not isinstance (ls, list) or not isinstance (n, int ): return [] ls_len = len (ls) print 'ls length = % 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 ,... (N-1 j in front), j + k # Step j, times n-1 ls_return = [] for I in xrange (0, n-1) * j, j ): ls_return.append (ls [I: I + j]) # Calculate j + k ls_return.append (ls [(n-1) * j:]) return ls_returndef pin (IP): try: xpin = subprocess. check_output ("ping-n 1-w 100% s" % IP, shell = True) failed t 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 The MS else: MS = mstime. group (). split ('=') [1] return MS. strip ('Ms ') def count (total_count, I): global RESULT nowsecond = int (time. time () nums = 0 oknums = 0 timeout = 0 lostpacket = 0.0 total_ms = 0.0 avgms = 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 = max (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 = 10 network = ''thread_num = 10 args = sys. argv [1:] try: (opts, getopts) = getopt. getopt (args, 'N': t: c: h? ') Failed T: print "\ nInvalid command line option detected. "usage () sys. exit (1) for opt, arg in opts: if opt in ('-n'): network = arg if opt in ('-H ','-? '): Usage () sys. exit (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 = div_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 ') print 'work Done. please check result % s and ping_result.xls. '% file
This code reference others' implementations. Although it is not very complicated, I would like to explain it briefly here.
- Excel reads and writes using xlrd and xlwt, basically using some simple APIs.
- Threading is used to implement multi-thread concurrency, which is very similar to the POSIX standard interface. Thread_func is a thread processing function. Its input contains a List of ip addresses. Therefore, each ip address is processed cyclically in the function.
- In addition, the Python commands is not compatible in Windows, so the subprocess module is used.
So far, I have not yet understood the character set in Python, so the code for regular expression matching is not strong enough, but I can barely work at the moment, and it is necessary to change it later!
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.