
📌 脚本功能
基于 IP + 端口 的 TCP 监测
宕机自动推送通知
PushDeer(钉钉/微信/Telegram 通知可替换)
Server酱(微信推送)
日志记录失败信息
可后台常驻运行
1️⃣ 脚本内容(示例)
#!/bin/bash
# 配置监控服务器列表:IP 端口 备注
servers=(
"223.5.5.5 80 主服务器"
"114.114.114.114 53 DNS对照组"
)
# 连接超时时间(秒)
timeout=3
# 检测函数
check_server() {
server=($1)
host=${server[0]}
port=${server[1]}
note=${server[2]}
# TCP 检测
if ! timeout $timeout bash -c "echo >/dev/tcp/$host/$port"; then
current_time=$(date '+%Y-%m-%d %H:%M:%S')
log="$current_time - $host:$port $note 连接失败"
message="监控点:[四川成都] $host:$port $note 无法访问 ${current_time}"
# PushDeer 推送
curl -G "https://api2.pushdeer.com/message/push" \
--data-urlencode "pushkey=******************" \
--data-urlencode "text=${message}" \
--data-urlencode "desp="
# Server酱推送
curl -X POST "https://sctapi.ftqq.com/******" -d "title=${message}"
# 写入日志
echo "$log" >> tcp.log
fi
}
# 主循环
while true; do
for server in "${servers[@]}"; do
check_server "$server" &
done
wait
sleep 5 # 每 5 秒检测一次
done
2️⃣ 脚本使用方法
2.1 运行脚本
nohup sh tcp_monitor.sh &
nohup可以让脚本在后台长期运行&表示后台执行
2.2 查看脚本运行情况
ps -aux | grep tcp_monitor.sh
2.3 查看日志
tail -f tcp.log
3️⃣ 脚本配置说明
servers
格式:"IP PORT 备注"
可自由添加多行,支持不同服务端口timeout
TCP 连接检测超时(秒),防止阻塞推送方式
PushDeer:可推送到微信、Telegram、钉钉
Server酱:可推送到微信
可自行增加 Email 或其他 API
sleep 5
设置检测间隔,可根据需要调整
4️⃣ 注意事项
确保 curl 已安装
sudo apt install curl # Ubuntu/Debian
sudo yum install curl # CentOS/RHEL
后台运行与日志管理
脚本会持续写入
tcp.log建议定期清理或轮转日志
监控稳定性
若监控节点过多,可调整并发检测逻辑
TCP 检测失败可能是临时网络抖动,推送策略可考虑加防抖逻辑
评论区