#!/bin/bash
# 定义需要测试的主机和端口
host="baidu.com"
port="80"
# 设置循环测试的间隔时间(以秒为单位)
interval=1
# 定义 nc 命令超时时间
timeout_duration=1
# 定义保存结果的文件路径
output_file="Sc4_port_test.txt"
# 循环测试端口连通性
while true; do
# 使用 timeout 命令设置 nc 命令的超时时间,测试端口连通性
timeout "$timeout_duration" nc -zv "$host" "$port" >/dev/null 2>&1
# 检查 nc 命令的退出状态码
if [ $? -eq 0 ]; then
result="$(date) Port $port is connected to host $host"
else
result="$(date) Connected port $port is inaccessible on host $host"
fi
# 将结果追加到文件中
echo "$result" >> "$output_file"
# 等待一段时间后进行下一次测试
sleep "$interval"
done