📅  最后修改于: 2023-12-03 14:45:33.705000             🧑  作者: Mango
Port scanning is a technique used to determine which ports on a remote computer are open and what services are running on those ports. This is useful for network administrators to identify potential vulnerabilities in their network and to ensure that security measures are in place.
Python is a powerful language that can be used for network and security analysis. Here, we will explore how to write a simple port scanner in Python.
We will start by writing a basic port scanner that uses the TCP protocol to check if a port is open or closed. The program will take an IP address and a range of ports as input and will print out a list of all open ports.
import socket
def tcp_port_scan(ip, port_range):
open_ports = []
for port in range(port_range[0], port_range[1]+1):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.settimeout(1)
result = sock.connect_ex((ip, port))
if result == 0:
print(f"Port {port} is open")
open_ports.append(port)
sock.close()
except:
pass
print(f"Open ports: {open_ports}")
To use the function, simply call tcp_port_scan
with the target IP address and the range of ports to scan:
tcp_port_scan("192.168.1.1", (1, 100))
This will scan ports 1 to 100 on the IP address 192.168.1.1
.
Next, we will write a similar port scanner that uses the UDP protocol. The function will take an IP address and a range of ports as input and will print out a list of all open UDP ports.
def udp_port_scan(ip, port_range):
open_ports = []
for port in range(port_range[0], port_range[1]+1):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
sock.settimeout(1)
sock.sendto(b"Hello", (ip, port))
data, addr = sock.recvfrom(1024)
print(f"Port {port} is open")
open_ports.append(port)
sock.close()
except:
pass
print(f"Open ports: {open_ports}")
To use the function, simply call udp_port_scan
with the target IP address and the range of ports to scan:
udp_port_scan("192.168.1.1", (1, 100))
This will scan ports 1 to 100 on the IP address 192.168.1.1
using the UDP protocol.
Using Python, we can easily create a simple port scanner that can be used for network and security analysis. Keep in mind that port scanning can be detected by some firewalls or intrusion detection systems, so be sure to obtain proper authorization before scanning a network.