用python写一个端口扫描工具代码
时间: 2024-11-27 15:20:22 浏览: 4
在Python中,我们可以使用`socket`模块来编写简单的端口扫描工具。这里是一个基础示例,展示了如何使用`socket`的`connect_ex()`函数来检查端口状态:
```python
import socket
def port_scanner(target_ip, target_port):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5) # 设置超时时间,防止阻塞过久
result = sock.connect_ex((target_ip, target_port))
if result == 0: # 如果返回值为0,表示端口是开放的
print(f"Port {target_port} on {target_ip} is open.")
else:
print(f"Port {target_port} on {target_ip} is closed or not responding.")
sock.close()
except Exception as e:
print(f"Error occurred: {str(e)}")
# 调用函数,例如扫描192.168.1.1的22端口
port_scanner('192.168.1.1', 22)
阅读全文