Python实现网络扫描工具的方法

2023-04-17 00:00:00 方法 网络 扫描工具

Python实现网络扫描工具的方法:

步骤一:导入需要使用的模块

import socket
import threading

步骤二:定义主机IP地址和端口范围

target = 'pidancode.com'
min_port = 50
max_port = 80

步骤三:定义一个函数,用于扫描某一个端口

def scan_port(port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(0.5)
        result = sock.connect_ex((target, port))
        if result == 0:
            print(f"Port {port}: Open")
        sock.close()
    except:
        pass

步骤四:使用多线程扫描端口

for port in range(min_port, max_port+1):
    thread = threading.Thread(target=scan_port, args=(port,))
    thread.start()

代码演示

import socket
import threading

target = 'pidancode.com'
min_port = 50
max_port = 80

def scan_port(port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(0.5)
        result = sock.connect_ex((target, port))
        if result == 0:
            print(f"Port {port}: Open")
        sock.close()
    except:
        pass

for port in range(min_port, max_port+1):
    thread = threading.Thread(target=scan_port, args=(port,))
    thread.start()

运行结果

Port 53: Open
Port 80: Open

说明:本程序使用多线程的方式实现了对pidancode.com网站端口50-80的扫描,在运行结果中发现端口53和80是开放的。

相关文章