首页 >后端开发 >Python教程 >使用 Python 的基本端口扫描器

使用 Python 的基本端口扫描器

Linda Hamilton
Linda Hamilton原创
2024-10-23 13:31:30255浏览

Basic Port Scanner using Python

源代码请点击这里

这是基本的端口扫描工具,允许用户扫描主机以查找开放端口以及该端口上运行的服务...

首先让我们看一下代码,然后将其分解为几部分来分析......

import socket
from datetime import datetime
import sys
import os 

def usage():
    """Prints the usage information for this script."""
    usage_info = """
    Tool Name: SimplePortScanner 

    Developed by : Bharath Kumar

    Usage:
        python3 port_scanner.py [options]

    Options:
        -h, --help           Show this help message and exit.
        -t, --target <ip>    Specify the target hostname or IP address (required).
        -p, --port <port>    Specify a port (or) range of ports to scan (e.g. -p 80 (or) -p 1-1024).

    Description:
        This script performs a port scan on a specified hostname or IP address
        for a specific port or a range of ports, checking which ports are open. 

    Examples:
        python3 port_scanner.py -t example.com (or) 192.0.0.1 
        python3 port_scanner.py -t example.com (or) 192.168.1.1 -p 80
        python3 port_scanner.py -t example.com (or) 192.168.1.1 --ports 1-1024
    """
    print(usage_info)

start_time = datetime.now()

def scan_port(ip, port):

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(1)
    try:
        result = s.connect_ex((ip, port))
        service = socket.getservbyport(int(port))
    except:
        service = "None"
    if result == 0:
        print(" Port: {}\t State: Open\t Service: {}".format(port, service))

    else:
        pass

    s.close()


def host(target):
    try:
        ip = socket.gethostbyname(target)
        print('_'*51)
        print("[#] Resolved {} to {}".format(target,ip))
        return ip
    except:
        print('_'*51)
        print("[#] Error: Unable to resolve hostname {}".format(target))
        sys.exit(1)

def check_host_up(ip):

    ping = os.system("ping {} -c 1 > /dev/null".format(ip))

    if ping == 0:
       print("[#] {} host is up and running".format(ip))
       return True
    else:
        print("[#] {} host is down".format(ip))
        print("Exiting...")
        exit()
        return False





if __name__ == "__main__":

    target_ip = None
    start_port = 1
    end_port = 65535

    try:
        for i, arg in enumerate(sys.argv):
            if arg in ("-t", "--target"):
                target_ip = sys.argv[i + 1]
            elif arg in ("-p", "--ports"):
                port_range = sys.argv[i + 1]
                if "-" in port_range:
                    start_port, end_port = map(int, port_range.split('-'))
                else:
                    start_port = end_port = int(port_range)

        if target_ip is None:
            print("[#] Error: Target hostname or IP address is required.")
            usage()
            sys.exit(1)

        if start_port is None or end_port is None:
            print("[#] Error: Port range is required.")
            usage()
            sys.exit(1)

        target_ip = host(target_ip)

        if not check_host_up(target_ip):
            sys.exit(1)

        print(f"[#] Scanning {target_ip} from port {start_port} to {end_port}...")
        print("[#] Scanning started at: {}".format(start_time))
        print('_'*51)

        for port in range(start_port, end_port + 1):
            scan_port(target_ip, port)

    except (IndexError, ValueError):
        print("[#] Error: Invalid arguments provided.")
        usage()
        sys.exit(1)

start_time = start_time.now() - start_time
print('_'*51)
print("Scanning is completed in ",start_time)

导入套接字:两个节点(服务器、客户端)相互通信的方式。

from datetime import datetime: 用于扫描所用的计算时间。

Import sys: 是对系统特定参数(argv)的访问。

导入os:用于执行ping命令。

def_usage(): 打印此脚本的使用信息。

start_time = datetime.now(): 用于获取当前时间和日期,以计算扫描所花费的时间。

def scan_port(ip, port):

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(1)
    try:
        result = s.connect_ex((ip, port))
        service = socket.getservbyport(int(port))
    except:
        service = "None"
    if result == 0:
        print(" Port: {}\t State: Open\t Service: {}".format(port, service))

    else:
        pass

    s.close()


此代码块定义函数 scan_port(ip, port),用于检查给定 ip 地址上的特定端口是否使用套接字打开。

套接字创建: socket.socket(socket.AF_INET, socket.SOCK_STREAM) 使用 TCP 为 IPv4 创建新套接字。

超时: s.settimeout(1) 将套接字时间设置为 1 秒,如果在该时间内连接未成功,它将停止尝试。

连接测试:s.connect_ex((ip, port))它尝试连接特定的ip和端口。如果成功,结果将为0;否则,它将是不同的值。

服务检测: socket.getservbyport(int(port))尝试检测指定端口上运行的服务。例如端口 80 的 HTTP。

错误处理:如果发生错误(例如,端口上没有服务), except 块将服务设置为“None”。

输出:如果端口打开(结果== 0),则打印端口号、状态(“打开”)和服务名称。

连接关闭: s.close() 关闭套接字以释放资源。

def host(target):
    try:
        ip = socket.gethostbyname(target)
        print('_'*51)
        print("[#] Resolved {} to {}".format(target,ip))
        return ip
    except:
        print('_'*51)
        print("[#] Error: Unable to resolve hostname {}".format(target))
        sys.exit(1)

此代码块定义了函数 host(target),它使用 socket.gethostname() 将给定的目标(主机名)解析为其相应的 IP 地址

def check_host_up(ip):

    ping = os.system("ping {} -c 1 > /dev/null".format(ip))

    if ping == 0:
       print("[#] {} host is up and running".format(ip))
       return True
    else:
        print("[#] {} host is down".format(ip))
        print("Exiting...")
        exit()
        return False

此函数 check_host_up(ip) 使用 os.system() ping 方法检查给定目标 ip 上的特定端口是打开还是关闭。

if __name__ == "__main__":

    target_ip = None
    start_port = 1
    end_port = 65535

    try:
        for i, arg in enumerate(sys.argv):
            if arg in ("-t", "--target"):
                target_ip = sys.argv[i + 1]
            elif arg in ("-p", "--ports"):
                port_range = sys.argv[i + 1]
                if "-" in port_range:
                    start_port, end_port = map(int, port_range.split('-'))
                else:
                    start_port = end_port = int(port_range)


命令行参数解析

sys.argv 数组包含传递给脚本的参数列表。我们循环遍历这些参数来检查目标 IP(-t 或 --target)和端口范围(-p 或 --ports)。

目标IP/主机名存储在target_ip中。
端口范围被解析并分为 start_port 和 end_port。如果不指定范围,则默认扫描1到65535之间的所有端口。

import socket
from datetime import datetime
import sys
import os 

def usage():
    """Prints the usage information for this script."""
    usage_info = """
    Tool Name: SimplePortScanner 

    Developed by : Bharath Kumar

    Usage:
        python3 port_scanner.py [options]

    Options:
        -h, --help           Show this help message and exit.
        -t, --target <ip>    Specify the target hostname or IP address (required).
        -p, --port <port>    Specify a port (or) range of ports to scan (e.g. -p 80 (or) -p 1-1024).

    Description:
        This script performs a port scan on a specified hostname or IP address
        for a specific port or a range of ports, checking which ports are open. 

    Examples:
        python3 port_scanner.py -t example.com (or) 192.0.0.1 
        python3 port_scanner.py -t example.com (or) 192.168.1.1 -p 80
        python3 port_scanner.py -t example.com (or) 192.168.1.1 --ports 1-1024
    """
    print(usage_info)

start_time = datetime.now()

def scan_port(ip, port):

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(1)
    try:
        result = s.connect_ex((ip, port))
        service = socket.getservbyport(int(port))
    except:
        service = "None"
    if result == 0:
        print(" Port: {}\t State: Open\t Service: {}".format(port, service))

    else:
        pass

    s.close()


def host(target):
    try:
        ip = socket.gethostbyname(target)
        print('_'*51)
        print("[#] Resolved {} to {}".format(target,ip))
        return ip
    except:
        print('_'*51)
        print("[#] Error: Unable to resolve hostname {}".format(target))
        sys.exit(1)

def check_host_up(ip):

    ping = os.system("ping {} -c 1 > /dev/null".format(ip))

    if ping == 0:
       print("[#] {} host is up and running".format(ip))
       return True
    else:
        print("[#] {} host is down".format(ip))
        print("Exiting...")
        exit()
        return False





if __name__ == "__main__":

    target_ip = None
    start_port = 1
    end_port = 65535

    try:
        for i, arg in enumerate(sys.argv):
            if arg in ("-t", "--target"):
                target_ip = sys.argv[i + 1]
            elif arg in ("-p", "--ports"):
                port_range = sys.argv[i + 1]
                if "-" in port_range:
                    start_port, end_port = map(int, port_range.split('-'))
                else:
                    start_port = end_port = int(port_range)

        if target_ip is None:
            print("[#] Error: Target hostname or IP address is required.")
            usage()
            sys.exit(1)

        if start_port is None or end_port is None:
            print("[#] Error: Port range is required.")
            usage()
            sys.exit(1)

        target_ip = host(target_ip)

        if not check_host_up(target_ip):
            sys.exit(1)

        print(f"[#] Scanning {target_ip} from port {start_port} to {end_port}...")
        print("[#] Scanning started at: {}".format(start_time))
        print('_'*51)

        for port in range(start_port, end_port + 1):
            scan_port(target_ip, port)

    except (IndexError, ValueError):
        print("[#] Error: Invalid arguments provided.")
        usage()
        sys.exit(1)

start_time = start_time.now() - start_time
print('_'*51)
print("Scanning is completed in ",start_time)

主机分辨率和可达性

一旦我们有了有效的IP地址,我们就需要检查主机是否可以访问。函数host(target_ip)将主机名解析为其IP地址,check_host_up(target_ip)验证主机是否在线。

def scan_port(ip, port):

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(1)
    try:
        result = s.connect_ex((ip, port))
        service = socket.getservbyport(int(port))
    except:
        service = "None"
    if result == 0:
        print(" Port: {}\t State: Open\t Service: {}".format(port, service))

    else:
        pass

    s.close()


端口扫描

端口扫描功能的核心发生在循环内:

此循环迭代指定的端口范围,对于每个端口,函数 scan_port(target_ip, port) 探测端口以检查它是打开还是关闭。

结论

通过遵循本指南,您已经学习了如何构建一个简单的 Python 端口扫描器,该扫描器接受命令行参数、验证输入以及扫描给定目标上的一系列端口。虽然这是一个基本实现,但它为线程或服务检测等更高级的功能奠定了基础。

请随意调整和扩展此脚本以满足您的特定需求。祝扫描愉快!

以上是使用 Python 的基本端口扫描器的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn