评估海外pop点网络质量,批量探测到整个国家运营商ip地址段时延

查询当地供应商所有AS号和IP地址段(https://bgp.he.net),如下

可以把prefix爬下来做下格式化,每段取一个ip地址来做探测

#只筛选时延大于20以上的网络,视为不正常时延
import subprocess,json
import threading
import os,sys
base_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
with open(base_dir+'/iplist') as e:
    ip = e.read().split()
pro,flag=divmod(len(ip), 40)
if flag !=0:
    pro +=1
thli =[]
from collections import defaultdict
restime = defaultdict(lambda:[])
def mtr_json(testip):
    tip,_=testip.split('/')
    tip = tip.split('.')
    tip[-1] = '1'
    ip = '.'.join(tip)
    cmd = 'mtr -n -c 2  -j %s'%ip
    ret = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()[0].decode()
    dic = json.loads(ret)['report']['hubs']
    timeout=True
    index = -1
    while timeout:
        if dic[index]['Avg'] !=0 and dic[index]['Loss%']<50:
            if dic[index]['Avg'] > 20:
                restime[testip] = str(dic[index]['Avg']) +'ms'
            timeout = False
        index -=1
startindex = 0
for x in range(pro):
    endindex = 40 if x ==0 else x*40
    f_ip = ip[startindex:endindex]
    for testip in f_ip:
        t = threading.Thread(target=mtr_json,args=(testip,))
        t.start()
        thli.append(t)
    for th in thli:
        th.join()
    startindex = endindex
print(restime)
print(len(restime),len(ip))

输出结果

 使用之前写的工具确认下所探测的ip地址归属地是否正确

 再附一个批量mtr的脚本

import subprocess,json
import threading
import os,sys
tli=[]
base_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
with open(base_dir+'/mtrlist') as e:
    ip = e.read().split()
print(ip)
def mtr_json(ip):
    cmd = 'mtr -r  -c 5 -w -b %s'%ip
    ret = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()[0].decode()
    with open(base_dir+'/mtr_log','a')  as sa:
        sa.write(ret)
for host in ip:
    t = threading.Thread(target=mtr_json,args=(host,))
    t.start()
    tli.append(t)
for t in tli:
    t.join()

Leave a Reply

Your email address will not be published. Required fields are marked *

X