写一个python代码,扫描设备开放的端口。
时间: 2024-05-07 22:15:59 浏览: 180
以下是一个简单的Python代码,可以扫描指定IP地址的设备开放的端口:
```python
import socket
target = input("Enter the IP address to scan: ")
min_port = int(input("Enter the minimum port number: "))
max_port = int(input("Enter the maximum port number: "))
print("Scanning target", target, "from port", min_port, "to port", max_port)
for port in range(min_port, max_port+1):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex((target, port))
if result == 0:
print("Port {} is open".format(port))
sock.close()
```
该代码使用了Python内置的socket库来创建一个TCP连接,然后使用connect_ex()函数来检查端口是否开放。如果端口开放,则输出相应的信息。
相关问题
用python写一个端口扫描工具代码
在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)
python写一个tcp端口扫描
可以使用Python的socket模块来实现TCP端口扫描,以下是一个简单的示例代码:
```python
import socket
target_host = "127.0.0.1"
target_ports = [80, 443, 8080]
for port in target_ports:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.settimeout(0.5)
try:
client.connect((target_host, port))
print(f"Port {port} is open")
except:
print(f"Port {port} is closed")
client.close()
```
这段代码会扫描目标主机上的80、443和8080端口,如果端口开放则输出"Port [port] is open",否则输出"Port [port] is closed"。
阅读全文