利用Python实现批量获取端口Banner的工具

  主要用到的模块包括:

  •   Socket 通讯模块
  •   threading多线程模块
  •   ipaddress ip地址模块
  •   optparse 命令行参数处理模块
import socket
import sys
import optparse
import ipaddress
import threading



class BannerGrab:
    def __init__(self) -> None:
        self.target = self.get_params()

    def get_params(self):
        parser = optparse.OptionParser('Usage: <Program> -t target ')
        parser.add_option('-t','--target', dest='target', type='string', help='Specify target IP address')
        options, args = parser.parse_args()
        if options.target is None:
            print(parser.usage)
            sys.exit(0)
        try:
            ipaddress.ip_address(options.target)    #判断用户输入的IP地址是否合法,如果不是,则退出程序
        except:
            print('[-] Please enter IP address')
            sys.exit(0)
        
        return options.target
    
    def banner_grab(self, port):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.settimeout(1)
            s.connect((self.target, port))
            banner = s.recv(1024).decode('utf-8')
            print("Port %d is open \t %s" % (port, banner))
        except:
            pass                  #如果连接出错,则表明端口关闭等,直接忽略即可
    
    def run(self):
        try:
            for port in range(1,65535):
                t = threading.Thread(target=self.banner_grab, args=(port, ))
                t.start()
        
        except KeyboardInterrupt:
            print("[-] Exit the program now!")
            sys.exit(0)

if __name__ == "__main__":
    banner = BannerGrab()
    banner.run()

 

posted @ 2022-05-16 19:14  Jason_huawen  阅读(110)  评论(0编辑  收藏  举报