>  기사  >  백엔드 개발  >  Python에서 네트워크 테스트를 구현하기 위한 스크립트 공유에 대한 자세한 설명

Python에서 네트워크 테스트를 구현하기 위한 스크립트 공유에 대한 자세한 설명

黄舟
黄舟원래의
2017-05-28 11:13:142101검색

이 글은 주로 Python을 사용하여 네트워크 테스트를 구현하는 방법을 소개합니다. 이 글은 참고 및 학습을 위한 자세한 샘플 코드를 제공합니다. 필요한 모든 친구가 함께 읽을 수 있습니다. 보세요.

머리말

최근에 한 반 친구가 나에게 네트워크 테스트 도구 작성을 도와달라고 요청했습니다. 업무 문제로 인해 간헐적으로 비교적 완성된 버전을 내놓는 데 오랜 시간이 걸렸습니다. 사실 저는 Python을 상대적으로 적게 사용하기 때문에 기본적으로 정보를 확인하면서 프로그램을 작성합니다.

프로그램의 주요 논리는 다음과 같습니다.

Excel 파일에서 IP 목록을 읽은 다음 멀티스레딩을 사용하여 ping을 호출하여 각 IP의 네트워크 매개변수를 계산하고 마지막으로 결과를 Excel로 출력합니다. 파일.

코드는 다음과 같습니다.

#! /usr/bin/env python
# -*- coding: UTF-8 -*-
# File: pingtest_test.py
# Date: 2008-09-28
# Author: Michael Field
# Modified By:intheworld
# Date: 2017-4-17
import sys
import os
import getopt
import commands
import subprocess
import re
import time
import threading
import xlrd
import xlwt

TEST = [
  '220.181.57.217',
  '166.111.8.28',
  '202.114.0.242',
  '202.117.0.20',
  '202.112.26.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',
]
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为简单测试的IP列表"
 print "\t-t times 测试次数;默认为1000;"
 print "\t-c concurrent number 并行线程数目:默认为10"
 print "\t-h|-?, 帮助信息"
 print "\t 输出为当前目录文件ping_result.txt 和 ping_result.xls"
 print "for example:"
 print "\t./ping_test.py -n TEST -t 1 -c 10"

def p_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),j+k
  #步长j,次数n-1
  ls_return = []
  for i in xrange(0,(n-1)*j,j):
   ls_return.append(ls[i:i+j])
  #算上末尾的j+k
  ls_return.append(ls[(n-1)*j:])
  return ls_return

def pin(IP):
 try:
  xpin=subprocess.check_output("ping -n 1 -w 100 %s" %IP, shell=True)
 except Exception:
  xpin = &#39;empty&#39;
 ms = &#39;=[0-9]+ms&#39;.decode("utf8")
 print "%s" %ms
 print "%s" %xpin
 mstime=re.search(ms,xpin)
 if not mstime:
  MS=&#39;timeout&#39;
  return MS
 else:
  MS=mstime.group().split(&#39;=&#39;)[1]
  return MS.strip(&#39;ms&#39;)
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 &#39;pin output = %s&#39; %MS
  if MS == &#39;timeout&#39;:
   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 &#39;nrows %s&#39; %nrows
 ips = []
 for i in range(nrows):
  ips.append(table.cell_value(i, 0))
  print table.cell_value(i, 0)
 return ips
 

if name == &#39;main&#39;:
 file = &#39;ping_result.txt&#39;
 times = 10
 network = &#39;&#39;
 thread_num = 10
 args = sys.argv[1:]
 try:
  (opts, getopts) = getopt.getopt(args, &#39;n:t:c:h?&#39;)
 except:
  print "\nInvalid command line option detected."
  usage()
  sys.exit(1)
 for opt, arg in opts:
  if opt in (&#39;-n&#39;):
   network = arg
  if opt in (&#39;-h&#39;, &#39;-?&#39;):
   usage()
   sys.exit(0)
  if opt in (&#39;-t&#39;):
   times = int(arg)
  if opt in (&#39;-c&#39;):
   thread_num = int(arg)
 f = open(file, &#39;w&#39;)
 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 [&#39;TEST&#39;] 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 == &#39;TEST&#39;:
   ips = TEST
  else:
   ips = readIpsInFile(network)
  print &#39;Starting...&#39;
  threads = []
  nest_list = p_list(ips, thread_num)
  loops = range(len(nest_list))
  print &#39;Total %s Threads is working...&#39; %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(&#39;%.2f&#39;%value[1]))
   sheet1.write(it, 2, str(&#39;%.2f&#39;%value[2]))
   sheet1.write(it, 3, str(&#39;%.2f&#39;%value[3]))
   it+=1
   f.write(line + &#39;\t&#39;+ str(&#39;%.2f&#39;%value[1]) + &#39;\t&#39;+ str(&#39;%.2f&#39;%value[2]) + &#39;\t&#39;+ str(&#39;%.2f&#39;%value[3]) + &#39;\n&#39;)
  f.close()
  workbook.save(&#39;ping_result.xls&#39;)
  print &#39;Work Done. please check result %s and ping_result.xls.&#39;%file

이 코드는 다른 사람의 구현을 참조한 것입니다. 특별히 복잡하지는 않지만 여기서는 간단히 설명하겠습니다.

  • Excel 읽기 및 쓰기는 기본적으로 간단한 api를 사용하여 xlrd 및 xlwt를 사용합니다.

  • 스레딩을 사용하여 POSIX 표준 인터페이스와 매우 유사한 다중 스레드 동시성을 달성합니다. thread_func는 스레드 처리 함수 입니다. 입력에는 IP 목록이 포함되어 있으므로 각 IP는 함수 내부의 루프 를 통해 처리됩니다.

  • 또한 Windows에서는 Python 명령이 호환되지 않으므로 하위 프로세스 모듈이 사용됩니다.

지금까지 Python의 문자 집합에 대한 이해가 충분하지 않아서 정규 표현식 일치 코드가 충분히 강력하지 않지만 현재로서는 거의 작동하지 않으며 다음 작업이 필요할 수 있습니다. 앞으로는 바꾸세요!

요약

위 내용은 Python에서 네트워크 테스트를 구현하기 위한 스크립트 공유에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.