利用Python实现检测IP报文TTL值的工具

  本代码主要利用scapy模块实现报文的截取以及分析,同时利用ipaddress模块判断IP地址是否为私有IP地址。

 1 from scapy.all import *
 2 import optparse
 3 import sys
 4 import ipaddress
 5 class TTLDetect:
 6     def __init__(self) -> None:
 7         self.interface = self.get_params()
 8         self.banner()
 9     
10 
11     def banner(self):
12         banner= """
13                 **************************************************
14 
15                 ***********TTL Detection Tool by Jason Wong*******        
16 
17                 **************************************************
18 
19               
20         """
21         print(banner)
22 
23     def get_params(self):
24         parser = optparse.OptionParser('Usage: <Program> -i interface')
25         parser.add_option('-i', '--interface', dest='interface', type='string', help='Specify interface to listen')
26         options, args = parser.parse_args()
27         if options.interface is None:
28             print(parser.usage)
29             sys.exit(0)
30         return options.interface
31     
32     def packet_handler(self, pkt):
33         if pkt.haslayer(IP):
34             src = pkt.getlayer(IP).src
35             dst = pkt.getlayer(IP).dst
36             ttl = pkt.getlayer(IP).ttl
37             if not ipaddress.ip_address(src).is_private:   #如果是私有地址,就不打印输出
38                 print("[-] Packet from %s\t with TTL:\t %s" % (src, ttl))
39     
40 
41     def run(self):
42         try:
43             sniff(iface=self.interface, prn=self.packet_handler, store=False)
44         except KeyboardInterrupt:
45             print("Exit program now")
46             sys.exit(0)
47         except Exception as e:
48             print(e)
49             sys.exit(0)
50 
51 
52 if __name__ == "__main__":
53     ttldetect = TTLDetect()
54     ttldetect.run()

 

posted @ 2022-05-24 11:02  Jason_huawen  阅读(284)  评论(0)    收藏  举报