1. 程式人生 > 其它 >利用Python與Scapy模組構建埠掃描器

利用Python與Scapy模組構建埠掃描器

 1 from scapy.all import *
 2 import sys
 3 import optparse
 4 import threading
 5 
 6 
 7 class PortScanner:
 8     def __init__(self) -> None:
 9         self.host = self.get_params()[0]
10         self.ports = self.get_params()[1]
11         
12         self.port_list = []
13         self.port_list = self.get_port_range()
14 self.banner() 15 16 17 def banner(self): 18 banner= """ 19 ************************************************** 20 21 ********** Port Scanner V1.0 by Jason Wong******** 22 23 **************************************************
24 """ 25 print(banner) 26 27 def get_port_range(self): #根據使用者輸入的引數型別,進行處理,形成待掃描的埠列表 28 if ',' in self.ports: 29 self.port_list = self.ports.split(',') 30 elif '-' in self.ports: 31 start_port = int(self.ports.split('-')[0]) 32 end_port = int(self.ports.split('
-')[1]) 33 for port in range(start_port, end_port): 34 self.port_list.append(port) 35 else: 36 self.port_list = self.ports 37 return self.port_list 38 39 def get_params(self): 40 parser = optparse.OptionParser('Usage: <Program> -H target -p port range') 41 parser.add_option('-H', '--host', dest='host', type='string', help='Specify host to scan') 42 parser.add_option('-p','--ports',dest='ports', type='string', help='Specify port range to scan') 43 options, args = parser.parse_args() 44 if options.host is None or options.ports is None: 45 print(parser.usage) 46 sys.exit() 47 return options.host, options.ports 48 49 def port_scan(self, port): 50 packet = IP(dst=self.host)/TCP(dport=port, flags='S') 51 response = sr1(packet,timeout=1,verbose=False) 52 if response: 53 if response.haslayer(TCP): 54 if response.getlayer(TCP).flags == 18: 55 print("\tPort %d is open" % port) 56 57 58 59 def run(self): 60 print("Start to scan : %s" % self.host) 61 62 for port in self.port_list: 63 t = threading.Thread(target=self.port_scan, args=(port,)) 64 t.start() 65 66 if __name__ == '__main__': 67 portscanner = PortScanner() 68 portscanner.run()