Jenkins 远程监控 Linux 的完整落地方案
一、方案总览与架构
二、快速落地步骤
#!/usr/bin/env bash
set -euo pipefail
PORT=$1; PROJECT=$2; JOB=$3; MOD=$4
LOG=~/log/${PROJECT}.log
mkdir -p ~/log
PID=$(/usr/sbin/lsof -iTCP:"$PORT" -sTCP:LISTEN -P -n 2>/dev/null | awk 'NR>1 {print $2; exit}')
if [[ -z "$PID" ]]; then
echo "$(date '+%F %T') 服务 DOWN,尝试重启 $PROJECT ..." >> "$LOG"
nohup /usr/bin/java -jar \
-Dsun.jnu.encoding=UTF8 -Dfile.encoding=UTF8 \
-Dspring.profiles.active=production,swagger"$MOD" \
~/"$PROJECT/$JOB.jar" >> /dev/null 2>&1 &
sleep 5
NEW_PID=$(/usr/sbin/lsof -iTCP:"$PORT" -sTCP:LISTEN -P -n 2>/dev/null | awk 'NR>1 {print $2; exit}')
if [[ -n "$NEW_PID" ]]; then
echo "$(date '+%F %T') 重启成功,PID=$NEW_PID" >> "$LOG"
else
echo "$(date '+%F %T') 重启失败" >> "$LOG"
fi
else
echo "$(date '+%F %T') 服务 UP,PID=$PID" >> "$LOG"
fi
# 每分钟检查一次
* * * * * /root/monitor.sh 9065 online_store cms JOB_NAME
curl -s 'https://oapi.dingtalk.com/robot/send?access_token=YOUR_TOKEN' \
-H 'Content-Type: application/json' \
-d "{\"msgtype\":\"text\",\"text\":{\"content\":\"[监控告警] 主机 $(hostname) 项目 $PROJECT 端口 $PORT 异常,已尝试重启\"}"
pipeline {
agent any
environment {
SSH_CRED = 'prod-ssh-key'
HOST = '192.168.1.10'
USER = 'deploy'
}
stages {
stage('Health Check') {
steps {
script {
def status = sh(
script: """ssh -o StrictHostKeyChecking=no ${USER}@${HOST} 'pgrep -f myapp.jar || echo DOWN'""",
returnStdout: true
).trim()
if (status == 'DOWN') {
// 触发远程自愈或告警
sh "ssh ${USER}@${HOST} '~/monitor.sh 8080 myapp api JOB-123 || true'"
// 钉钉告警
httpRequest(
httpMode: 'POST',
url: 'https://oapi.dingtalk.com/robot/send?access_token=YOUR_TOKEN',
contentType: 'APPLICATION_JSON',
requestBody: """{"msgtype":"text","text":{"content":"[Jenkins] ${HOST} myapp DOWN,已尝试自愈"}}"""
)
}
}
}
}
}
}
三、进阶监控与可视化
四、安全与运维要点