端口扫描器是一种检测服务器或主机虚拟端口是开启或关闭的工具。
原理是程序尝试与目标主机建立连接,如果目标主机有回复则说明端口开放。
使用python写一个端口扫描器
大致可以使用两种方式判断端口是否在开启状态
方式一:
s = socket.socket() s.connect((‘ip, port)) result_code= s.recv(1024)方式二:
s = socket.socket() result_code = s.connect_ex((ip, port))在这里我使用了方式二来实现端口扫描器
代码如下:
import socket import sys def portscan(ip): PORT_OPEN_MSG = "%6d [OPEN]" PORT_CLOSE_MSG = "%6d [CLOSE]" result_list = list() port_list = [21,22,25,53,80,110,113,135,139,143,179,199,443,445,465,514,548,554,587,646,993,995,1025,1026,1433,1720,1723,2000,3306,3389,5060,5666,5900,6001,8000,8008,8080,8443,8888,10000,32768,49152,49154] #扫描所有端口太浪费时间,所以选择一个要扫描的端口列表进行扫描 for port in port_list: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(0.1) result_code = s.connect_ex((ip, port)) if result_code == 0: print(PORT_OPEN_MSG % port) result_list.append(port) else: print(PORT_CLOSE_MSG % port) result_list.append(port) except Exception as e: print(e) finally: s.close() return result_list def main(): if len(sys.argv) > 1: portscan(sys.argv[1]) else: print("param less") if __name__ == '__main__': main()运行效果如下: