搜尋
首頁後端開發Python教學Python實現網路測試的腳本分享詳解

這篇文章主要為大家介紹了關於利用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讀寫使用了xlrd和xlwt,基本上就是使用了一些簡單的api

  •     使用了threading實作多執行緒並發,和POSIX標準介面非常相似。 thread_func是執行緒的處理函數,它的輸入包含了一個ip的List,所以在函數內部透過循環處理各個ip。

  •     另外,Python的commands在Windows下方並不相容,所以使用了subprocess模組。

到目前為止,我對Python裡面字元集的理解還不到位,所以正規表示式匹配的程式碼並不夠強壯,不過目前勉強可以工作,以後有必要再改咯!

總結

#

以上是Python實現網路測試的腳本分享詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python和時間:充分利用您的學習時間Python和時間:充分利用您的學習時間Apr 14, 2025 am 12:02 AM

要在有限的時間內最大化學習Python的效率,可以使用Python的datetime、time和schedule模塊。 1.datetime模塊用於記錄和規劃學習時間。 2.time模塊幫助設置學習和休息時間。 3.schedule模塊自動化安排每週學習任務。

Python:遊戲,Guis等Python:遊戲,Guis等Apr 13, 2025 am 12:14 AM

Python在遊戲和GUI開發中表現出色。 1)遊戲開發使用Pygame,提供繪圖、音頻等功能,適合創建2D遊戲。 2)GUI開發可選擇Tkinter或PyQt,Tkinter簡單易用,PyQt功能豐富,適合專業開發。

Python vs.C:申請和用例Python vs.C:申請和用例Apr 12, 2025 am 12:01 AM

Python适合数据科学、Web开发和自动化任务,而C 适用于系统编程、游戏开发和嵌入式系统。Python以简洁和强大的生态系统著称,C 则以高性能和底层控制能力闻名。

2小時的Python計劃:一種現實的方法2小時的Python計劃:一種現實的方法Apr 11, 2025 am 12:04 AM

2小時內可以學會Python的基本編程概念和技能。 1.學習變量和數據類型,2.掌握控制流(條件語句和循環),3.理解函數的定義和使用,4.通過簡單示例和代碼片段快速上手Python編程。

Python:探索其主要應用程序Python:探索其主要應用程序Apr 10, 2025 am 09:41 AM

Python在web開發、數據科學、機器學習、自動化和腳本編寫等領域有廣泛應用。 1)在web開發中,Django和Flask框架簡化了開發過程。 2)數據科學和機器學習領域,NumPy、Pandas、Scikit-learn和TensorFlow庫提供了強大支持。 3)自動化和腳本編寫方面,Python適用於自動化測試和系統管理等任務。

您可以在2小時內學到多少python?您可以在2小時內學到多少python?Apr 09, 2025 pm 04:33 PM

兩小時內可以學到Python的基礎知識。 1.學習變量和數據類型,2.掌握控制結構如if語句和循環,3.了解函數的定義和使用。這些將幫助你開始編寫簡單的Python程序。

如何在10小時內通過項目和問題驅動的方式教計算機小白編程基礎?如何在10小時內通過項目和問題驅動的方式教計算機小白編程基礎?Apr 02, 2025 am 07:18 AM

如何在10小時內教計算機小白編程基礎?如果你只有10個小時來教計算機小白一些編程知識,你會選擇教些什麼�...

如何在使用 Fiddler Everywhere 進行中間人讀取時避免被瀏覽器檢測到?如何在使用 Fiddler Everywhere 進行中間人讀取時避免被瀏覽器檢測到?Apr 02, 2025 am 07:15 AM

使用FiddlerEverywhere進行中間人讀取時如何避免被檢測到當你使用FiddlerEverywhere...

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器