美文网首页
教你用shell脚本检测服务器程序是否在运行

教你用shell脚本检测服务器程序是否在运行

作者: Mracale | 来源:发表于2023-03-13 11:34 被阅读0次

    shell脚本定时检测python程序是否运行
    shell脚本

    #!/bin/bash
    
    echo "开始检查运费fright_run程序是否运行..."
    
    cd /opt/gh2/app/goods-freight-py
    
    processID=$(ps -ef | grep freight_run.py | grep -v "grep" | awk "{print $2}")
    echo $processID
    # 判断$processID为空,此处意思为如果$processID为空,那么重启
    if [ -z "$processID" ]
    then
        # 启动运费fright_run程序
        echo "运费fright_run程序未运行, 重新启动中..."
        #nohup python3 freight_run.py >/dev/null &
        nohup python3 freight_run.py >/store/logs/goods-freight-py/startpy.log &
        echo "fright_run程序重启成功..."
        # 发送邮件, 最好写绝对路径,否则可能会重启成功但是发邮件失败
        #cd /opt/gh2/app/goods-freight-py/common
        #python3 send_email.py "fright_run程序重启成功..."
        python3 /opt/gh2/app/goods-freight-py/common/send_email.py "fright_run程序重启成功..." "${ipAdress}"
    
    
    else
        echo "fright_run程序正在运行中..."
    fi
    
    # ps -ef 展示进程
    # | grep your_keywords 按关键字筛选
    # | grep -v “grep” 屏蔽grep程序本身的进程
    # | awk ‘{print $2}’ 只打印第二列
    # process_id=${语句} 将语句执行的返回值赋值给process_id,注意等号前后不能有空
    # [ -z "$process_id”] 判断$process_id为空
    # [[ -z "$process_id”]] 判断$process_id不为空 , 注意这里前后有两个中括号,Shell的这个语法有点奇怪
    # kill -9 $process_id 杀掉变量$process_id指定的进程
    

    linux 上 crontab启动sh:
    先把shell脚本放到 /opt/gh2/app/goods-freight-py
    方式1:vi /etc/crontab 后进入编辑模式,在下边添加
    */1 * * * * sh /opt/gh2/app/goods-freight-py/shell/check_freight_run.sh >/store/logs/goods-freight-py/freightRun.log 2>&1
    方式2:连上服务器后,直接
    crontab -e 后进入编辑模式,在下边添加
    */1 * * * * sh /opt/gh2/app/goods-freight-py/shell/check_freight_run.sh >/store/logs/goods-freight-py/freightRun.log 2>&1

    查看所有定时任务: crontab -l
    查看crontab默认日志:tail -f /var/log/cron

    注意事项:
    如果是window下编写的shell脚本,复制到linux上运行,会报错
    解决办法: vim freight.sh 后,在命令行中 先 :set fileformat=unix ,然后再 :wq
    试运行freight.sh: bash freight.sh

    相关文章

      网友评论

          本文标题:教你用shell脚本检测服务器程序是否在运行

          本文链接:https://www.haomeiwen.com/subject/yhdcrdtx.html