Shell钉钉机器人消息通知

Shell 脚本语言是实现Linux系统管理及自动化所必须的重要工具。熟练地编写Shell语言可以提升运维人员的工作效率,适应复杂的工作环境。

#!/bin/sh
 
#=============== java程序 begin ====================#
  function callJavaProgram(){
    nohup java -Dfile.encoding=UTF-8 -jar qingninmaicai-0.0.1-SNAPSHOT.jar  >/dev/null 2>&1 &
  }
#=============== java程序 end =======================#
 
 
#=============== 发送钉钉的消息 begin ================#
# 注意: ${nowtime}对应的日期参数不能有空格
# 注意: ${programe}为执行的jar程序的主程序名
url='https://oapi.dingtalk.com/robot/send?access_token=XXXXXXXXXXX'
programe=qingninmaicai
server=vip.zjtie.top
content='程序中断'
logfile=testjava.log
 
function sendDingtalk(){
    curl ${1} \
       -H 'Content-Type: application/json' \
       -d "
      {\"msgtype\": \"text\", 
        \"text\": {
            \"content\": \"消息内容:项目-${2},服务地址-${3},异常-${4},logfile-${5}\"
         }
      }"
}
#sendDingtalk ${url} ${programe} ${server} ${nowtime} ${content}
#=============== 发送钉钉的消息 end ==================#
 
 
# 最大尝试次数
maxRetry=3
# 尝试次数计数器
retryTimes=0
 
(
while true;
do
  # 检测java程序执行的进程个数,如果小于1,则未启动
  count=`ps -ef | grep ${programe} | grep -v grep|wc -l`
  #echo '进程个数:'$count >> ${logfile}
  nowtime=`date --date='0 days ago' "+%Y-%m-%d_%H:%M:%S"`
 
  if [ ${count} -lt 1 ]; then
 
    retryTimes=$[$retryTimes+1]
 
    content='检测到程序【'${programe}'】未启动,正在尝试启动......第'"${retryTimes}"'次'
    echo ${nowtime} ${content} >> ${logfile}
    sendDingtalk ${url} ${programe} ${server} ${nowtime} ${content}
 
    if [ $retryTimes -ge $maxRetry ]; then
        content='检测到程序【'${programe}'】异常,尝试启动'"${maxRetry}"'次失败,程序退出,请手工解决'
        echo ${content} >> ${logfile}
        sendDingtalk ${url} ${programe} ${server} ${nowtime} ${content}
        break
    fi
 
    #============== 这里执行java程序 =========================#
    callJavaProgram
    #============== 这里执行java程序 =========================#
 
  else
     if [ $retryTimes -gt 0 ]; then
        content='程序【'${programe}'】启动成功......第'"${retryTimes}"'次'
        echo ${content} >> ${logfile}
        sendDingtalk ${url} ${programe} ${server} ${nowtime} ${content}
     else
        echo ${nowtime} '程序【'${programe}'】......正在运行中' >> ${logfile}
     fi
     let retryTimes=0
  fi
 
  sleep 10
 
done
) & >> shell.log

©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页