# 这一脚本制作是完成Linux中traceroute程序流程的,是检测从大家这一设备到我们要检测的IP地址正中间都必须历经这些路由器。
# 基本原理:大家的设备发送UDP高端口的数据文件 ,发送给目的地址,最先设定ttl为1,随后多次提升 ,在沒有抵达大家的目的IP
# 地址的路由器,会发送ICMP的请求超时报文,随后大家从这当中获取IP地址 ,由于大家发送的是高端口的报文,抵达目的地址的情况下,
# 目的地址会发送ICMP的端口不能达报文 ,那样大家就检测出从大家源端口到目的端口的路由器。
from scapy.all import *
import struct,re,random

# 跟大家完成ping程序流程的念头是一样的,最先结构一个发送一个UDP报文的涵数,
# 入参为目的地址 ,ttl数 。
def traceroute_one(dst,ttl_no,dport):
# 界定分包時间。
send_time = time.time()
try:
# 发送一个包 ,接受一个包。
traceroute_one_reply = sr1(IP(dst=dst, ttl=ttl_no) / UDP(dport=dport) / b'hello world', timeout=1,
verbose=False)
# 分辨ICMP包是否请求超时回应 。
if traceroute_one_reply.getlayer(ICMP).type == 11 and traceroute_one_reply.getlayer(ICMP).code == 0:
# 获取源地址
src_ip = traceroute_one_reply.getlayer(IP).src
# 界定接受時间。
recv_time = time.time()
# 时间计算ms数
mid_time = (recv_time - send_time) * 1000
# 回到。
return 1,src_ip,mid_time
# 这儿接接受的是最后一跳 。ICMP应该是端口不能达。
elif traceroute_one_reply.getlayer(ICMP).type == 3 and traceroute_one_reply.getlayer(ICMP).code == 3:
# 下面解决是一样的。
src_ip = traceroute_one_reply.getlayer(IP).src
recv_time = time.time()
mid_time = (recv_time - send_time) * 1000
return 2, src_ip, mid_time
except Exception as e:
return None


def traceroute(dst,hops):
# 目的端口从33434刚开始算起,入参为目的地址,大家要想搜索的路由器的总数 。
dport = 33434
hop = 0
# 开展循环系统包。
while hop < hops:
hop = 1
# 这儿必须更改端口。
dport = hop
# 发送一个包 ,获得返回值 。
traceroute_result = traceroute_one(dst,hop,dport)
# 假如出現了不正确,复印*号 。
if traceroute_result == None:
print('*')
# 这儿意味着正中间路由器,大家开展打印信息。
elif traceroute_result[0] == 1:
print("%d %s %4.2fms" % (hop,traceroute_result[1],traceroute_result[2]))
# 最终一个包 ,为端口不能达,打印信息后,必须撤出循环系统 ,由于早已抵达目的地址了,尽管很有可能沒有做到大家界定的总数。
elif traceroute_result[0] == 2:
print("%d %s %4.2fms" % (hop, traceroute_result[1], traceroute_result[2]))
break
time.sleep(1)
if __name__ == "__main__":
traceroute('180.101.49.12',10)
# 接下去大家就可以应用wirshark开展抓包软件看来一下 。

 

文章来源于网络,如有侵权请联系站长QQ61910465删除
本文版权归趣快排营销www.SEOguruBLOG.com 所有,如有转发请注明来出,竞价开户托管,seo优化请联系QQ㊣61910465