YunMai365/脚本/测试端口是否开启(批量).txt

31 lines
998 B
Plaintext

import socket
def test_port(ip, port):
# 创建一个 socket 对象
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5) # 设置超时时间
try:
# 尝试连接指定的 IP 和端口
result = sock.connect_ex((ip, port))
if result == 0:
print(f"端口 {port} 在地址 {ip} 上是开放的")
else:
print(f"无法连接到 {ip}:{port}")
except Exception as e:
print(f"连接测试失败: {e}")
finally:
sock.close() # 关闭 socket 连接
if __name__ == "__main__":
filename = 'C:/Users/andin/Desktop/zhuwenbao.txt'
with open(filename, 'r') as file:
for line in file:
parts = line.strip().split()
if len(parts) >= 2:
ip = parts[0] # 第一部分是 IP 地址
port = int(parts[1]) # 第二部分是端口号
test_port(ip, port) # 调用函数 test_port