编写shell脚本kill掉占用cpu超过90%以上的程序

由于集群用户经常会不懂如何提交作业,将作业直接运行到登录节点上,这样导致登录节点的cpu及内存占用很大,导致其他用户甚至无法登录。所以就想到了一种解决方法,写一个shell脚本,常驻登录节点,监控cpu占用率,如果某一进程占用cpu超过90%,且运行时间超过十五秒,就直接kill掉。shell脚本代码如下:

#!/bin/sh

while true

do

    sleep3

   #循环查看占用cpu超过90%的进程ID
   /bin/ps axf -o "pid %cpu" | awk '{if($2>=90) print $1}' | while read procid
   do

     #进程详细信息
     pro=$(ps -A|grep "\\<$procid\\>" |sort -k3,3|head -n1)
     #获取进程运行的时间,如果大于15秒,设time为1,如若不是则设time为0
     time="$(echo $pro|awk '{
        split($3,tab,/:/); if (tab[3]>=15) {print 1}else{print 0}
     }')"

    #如果time1,则kill掉该进程

    if [ $time = '1' ];then

      kill -9 $procid
    fi
   done
done

最后运行 nohup ./你写的shell脚本  > cpucheck.log 2>&1 &   以保证它在后台长期运行

猜你喜欢

转载自www.cnblogs.com/ninicwang/p/10736388.html