Mac 下自动启动和关闭程序的脚本

通过 Vagex 的 firefox 插件刷积分,遇到一个问题,插件假死,需要重启火狐,不能人工一直看,so 写了一个脚本,加入到的 crontab 让系统自动监控

Posted on 2017-11-29 14:00:00 in Shell   阅读(4907)

应用背景:通过 Vagex 的 firefox 插件刷积分,遇到一个问题,插件假死,需要重启火狐,不能人工一直看,so 写了一个脚本,加入到的 crontab 让系统自动监控

# 此脚本用于 自动重启火狐浏览器 nothing more

# 脚本所在目录 此参数之后可以 当成脚本参数传递
dir=/Users/chen/Desktop/mySh
#  脚本执行日志路径文件名称 此参数之后可以 当成脚本参数传递
logPath=${dir}/firefox.log
# 启动的程序 此参数之后可以 当成脚本参数传递
app=/Applications/Firefox.app
# grep 启动程序的 关键字 一定要很准确 确保 结果最好只有一个 此参数之后可以 当成脚本参数传递
grepAppName=firefox

date=`date +%Y-%m-%d:%H:%M:%S`
hour=`date +%H`
app=/Applications/Firefox.app
echo '-------------------------------------------------------' >> ${logPath}
echo $date' 启动脚本' >> ${logPath}

# 杀死火狐
pkill -f ${grepAppName}
echo $date' 杀死进程' >> ${logPath}

if [ $hour -ge 10 -a $hour -lt 13 ]
then
    echo $date' 当前时间 不执行 免得浪费流量 10点-13点 赚不到东西' >> ${logPath}
    echo '-------------------------------------------------------\n'  >> ${logPath}
    exit 0
fi


if test ! -w ${logPath}
then
    touch ${logPath}
    chmod 777 ${logPath}
fi

# 第一次启动
open -j ${app} >> ${logPath} 2>&1
isRetry=0
function start(){
        pid=`pgrep -f ${grepAppName}`
        if test -z $pid
        then       
               date=`date +%Y-%m-%d:%H:%M:%S`
               echo $date' 当前没有进程号' >> ${logPath}

               if [ $isRetry == 1 ]
               then
                     echo $date' 重试启动脚本失败 开始重试' >> ${logPath}
               fi
               open -j ${app} >> ${logPath} 2>&1
               isRetry=1
               start
        else
               date=`date +%Y-%m-%d:%H:%M:%S`
               if [ $isRetry == 1 ]
               then
                   echo $date' 重试启动成功' >> ${logPath}
               else
                   echo $date' 没有错误' >> ${logPath}
               fi
               echo $date' 启动成功 PID 存在'$pid >> ${logPath}
        fi

}
# 调用方法
start
#检测网络链接&&ftp上传数据    
function networkAndFtp()    
{    
    #超时时间    
    timeout=5    

    #目标网站    
    target=www.baidu.com    

    #获取响应状态码    
    ret_code=`curl -I -s --connect-timeout $timeout $target -w %{http_code} | tail -n1`    

    date=`date +%Y-%m-%d:%H:%M:%S`
    ctype='执行前'
    if [ "x$ret_code" = "x200" ]; then   

        ctype='网络畅通'
    else    
        ctype='网络不畅通'    

    fi  
    echo $date" $ctype" >> ${logPath}
}  
networkAndFtp

echo '-------------------------------------------------------\n'  >> ${logPath}