Python ping3批量測試IP地址的訪問延遲

        某域名背後的服務器都佈置在國外,DNS服務器會將此域名解析到不固定的IP地址,其中某些IP地址在國內訪問速度挺快,有些很慢,還有一些則根本沒法訪問。爲提升訪問的穩定性,我決定先找出訪問速度最快的IP,而後修改hosts文件指向這個IP,省去DNS服務器的解析。
        首先經過https://ping.chinaz.com/找出目標域名的所有IP地址,保存到txt文件中,每一個IP地址佔一行(也能夠使用逗號分割)。而後用python3的open讀入文件,用ping3包的ping函數測試每一個IP地址的訪問延遲,測試n次後求平均值。對於訪問超時的IP地址,直接賦給它一個很長的時間,好比5000ms. 將IP地址及測試結果再寫入另外一個文本文件。若從未使用過ping3,請先安裝:pip install ping3 
代碼以下:

python

import ping3

fread=open(r"E:\PythonDevelop\IPList.txt",'r')
fwrite=open(r"E:\PythonDevelop\IPTest.txt",'w')
TargetIP=fread.readline()
n=3
while TargetIP:
    TotalTime=0.0
    for k in range(n):
        IPstrip=TargetIP.strip()
        PingTime=ping3.ping(IPstrip,timeout=1,unit='ms')
        if not PingTime:
            PingTime=5000.0
        TotalTime=TotalTime+PingTime
    print(IPstrip+','+str(int(TotalTime/n)))
    fwrite.writelines(IPstrip+','+str(int(TotalTime/3))+'\n')
    TargetIP=fread.readline()
fread.close()
fwrite.close()

ping函數的說明以下:
ping(dest_addr: str, timeout: int = 4, unit: str = 's', src_addr: str = None, ttl: int = 64, seq: int = 0, size: int = 56, interface: str = None) -> float
    Send one ping to destination address with the given timeout.

服務器

    Args:
        dest_addr: The destination address, can be an IP address or a domain name. Ex. "192.168.1.1"/"example.com"
        timeout: Time to wait for a response, in seconds. Default is 4s, same as Windows CMD. (default 4)
        unit: The unit of returned value. "s" for seconds, "ms" for milliseconds. (default "s")
        src_addr: WINDOWS ONLY. The IP address to ping from. This is for multiple network interfaces. Ex. "192.168.1.20". (default None)
        interface: LINUX ONLY. The gateway network interface to ping from. Ex. "wlan0". (default None)
        ttl: The Time-To-Live of the outgoing packet. Default is 64, same as in Linux and macOS. (default 64)
        seq: ICMP packet sequence, usually increases from 0 in the same process. (default 0)
        size: The ICMP packet payload size in bytes. If the input of this is less than the bytes of a double format (usually 8), the size of ICMP packet payload is 8 bytes to hold a time. The max should be the router_MTU(Usually 1480) - IP_Header(20) - ICMP_Header(8). Default is 56, same as in macOS. (default 56)







less

    Returns:
        The delay in seconds/milliseconds or None on timeout.
dom

    Raises:
        PingError: Any PingError will raise again if `ping3.EXCEPTIONS` is True.
函數

相關文章
相關標籤/搜索