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

27 lines
907 B
Plaintext
Raw Normal View History

2024-10-28 14:20:49 +08:00
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, int(port))) # 确保 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__":
# 测试端口,替换下面的 IP 和端口号为你想要测试的值
test_ip = "121.36.27.6"
target_port =80
# 这里的 target_port 是一个整数,表示要测试的端口号
test_port(test_ip, target_port) # 调用函数 test_port