setup_monitor.sh 1.5 KB
#!/bin/bash

# 定义脚本路径
SCRIPT_PATH="/opt/monitor.sh"
CRON_LOG="/var/log/monitor.log"

# 创建 monitor.sh 文件
(
    cat <<EOF
#!/bin/bash

# 定义API的URL
API_URL="https://lh.admin.yu2le.com/api/monitor/server/upload"

# 获取系统性能信息的函数
get_system_performance() {
    # 获取CPU使用率
    CPU_USAGE=\$(top -bn1 | grep "Cpu(s)" | awk '{print \$2 + \$4}')

    # 获取内存使用率
    MEMORY_USAGE=\$(free | grep Mem | awk '{print \$3/\$2 * 100.0}')

    # 获取磁盘使用率
    DISK_USAGE=\$(df -h | grep '^/dev/' | grep -v 'boot' | awk '{print \$5}' | tr -d '%' | paste -sd+ | bc)

    # 获取系统连接数
    CONNECTION_COUNT=\$(netstat -an | grep ESTABLISHED | wc -l)

    # 返回JSON格式的数据
    echo "{\"cpu_usage\": \"\${CPU_USAGE}\", \"memory_usage\": \"\${MEMORY_USAGE}\", \"disk_usage\": \"\${DISK_USAGE}\", \"connection_count\": \"\${CONNECTION_COUNT}\"}"
}

# 获取当前系统性能数据
DATA=\$(get_system_performance)

echo \$DATA

# 使用curl将数据上传到指定的API
curl -X POST -H "Content-Type: application/json" -d "\$DATA" --insecure "\$API_URL"
EOF
) > $SCRIPT_PATH

# 设置脚本执行权限
chmod +x $SCRIPT_PATH

# 添加定时任务
(crontab -l ; echo "*/1 * * * * $SCRIPT_PATH >> $CRON_LOG 2>&1") | crontab -

# 重启 cron 服务
systemctl restart crond

$SCRIPT_PATH

echo "Monitor setup completed."
# 解决:curl: (35) Peer reports incompatible or unsupported protocol version. 方法: yum update -y nss curl libcurl