autoDeploy/checkPort.sh
2025-02-25 21:52:14 +08:00

37 lines
904 B
Bash
Executable File

#!/bin/bash
function checkPort() {
ip_address=$1
port=$2
# 使用 telnet 检测连接,捕获输出
output=$(timeout 3 telnet $ip_address $port 2>&1)
# 输出捕获的内容(仅用于调试,可以删除)
echo "Telnet Output: $output"
# 根据输出内容判断是否连接成功
if echo "$output" | grep -q -E "Unable to connect|Connection closed by"; then
# 如果输出中包含 "Unable to connect" 或者 "Connection closed by",返回 0 表示连接失败
return 0
else
# 否则返回 1 表示连接成功
return 1
fi
}
# 调用 checkPort 函数,判断端口是否活跃
checkPort $1 $2
res=$?
# 根据端口状态输出结果
if [ "$res" -eq 1 ]; then
echo "service on $1 $2 worked normally"
else
echo "service port: $2 is not active, try to restart it"
eval $3 # 执行重启服务动作
fi
exit