#!/bin/bash  
  
# MySQL查询结果文件路径  
result_file="/root/result.txt"  
  
# 微信告警信息  
weixin_webhook="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=替换成自己的KEY"  

APPLICATION_JSON_TYPE="Content-Type: application/json"

# 读取查询结果文件  
while IFS= read -r line; do  
  address=$(echo "$line" | awk '{print $1}')  
  port=$(echo "$line" | awk '{print $2}')  
  username=$(echo "$line" | awk '{print $3}')  
  password=$(echo "$line" | awk '{print $4}')  
  typename=$(echo "$line" | awk '{print $5}') 
  # 执行MySQL访问命令  
  mysql -h "$address" -P "$port" -u "$username" -p"$password" -e "SELECT 1;" > /dev/null  
  if [ $? -ne 0 ]; then  
    echo "MySQL连接失败!发送微信告警。"  
    # 在此处添加发送微信告警通知的代码 
    title="## MySQL连接失败!! \n"
    addr="地址:${address} \n"
    portnum="端口:${port} \n"
    user="用户名:${username} \n"
    #passwd="密码:${password} \n"
    nametype="业务库:${typename}\n"
    tips="> 请检查数据库状态!!!"  
    MSG="$title $addr $portnum $user $passwd $nametype $tips"
    #echo "${MSG}"
    RESULT="{\"msgtype\": \"markdown\",\"markdown\": {\"content\": \"${MSG}\"}}"
    #echo "$RESULT"
    res_status_code=$(curl -s -o /dev/null -w "%{http_code}" -X POST -H "${APPLICATION_JSON_TYPE}" --url "${weixin_webhook}"  -d "${RESULT}")
    echo "发送结果返回状态码:${res_status_code}"
    if [[ $res_status_code == 200 ]]; then 
       echo "告警发送成功!!!!"
    else
       echo "告警发送失败了!!"
    fi
  else  
    echo "MySQL连接成功。"  
  fi  
done < "$result_file"  # 读取查询结果文件