当cpu高于x%时杀死进程的Bash脚本

时间:2018-07-21 21:31:59

标签: bash

我以为我是对此的第一手武器。

我正在尝试创建一个脚本,当该脚本连续两次检测到使用的CPU百分比高于70%时,它将杀死所有屏幕和python进程。

关于脚本的当前状态,我没有收到错误,但我知道它无法正常工作。

有人可以帮我吗?

#!/bin/bash
clear
a=0
b=2
now=$(date +"%T")
echo [$now] Start

while :
do      ###i take this 3 line online to check the cpu usage %
    cores=$(nproc) 
    load=$(awk '{print $3}'< /proc/loadavg)
    usage=$(echo | awk -v c="${cores}" -v l="${load}" '{print l*100/c}' | awk -F. '{print $1}')
    if [[ ${usage} -ge 70 ]];
    then
        let "a += 1"
        if [[ "$a" -eq "$b" ]];
        then 
            echo
            echo ============================================
            echo
            now=$(date +"%T")
            echo -e "\e[33m[$now]\e[39m" CPU usage "\e[33m[$usage]\e[39m" 
            echo
            let "a=0"
            echo pkill screen  ###this 2 command is what i need to do
            echo pkill python  ###when the cpu is higher than 70%
            echo
            echo "processi chiusi"
            echo ============================================
            sleep 15
        else

            echo
            echo ============================================
            echo
            echo 
            echo
            now=$(date +"%T")
            echo -e "\e[33m[$now]\e[39m" CPU usage "\e[33m[$usage]\e[39m" 
            echo
            echo ============================================
            sleep 15
        fi

    else
        echo
        echo
        echo
        echo ============================================
        echo
        now=$(date +"%T")
        echo -e "\e[33m[$now]\e[39m" CPU usage "\e[33m[$usage]\e[39m" 
        let "a=0"
        echo
        echo "contatore: "
        echo "[$a]"
        echo ============================================
        sleep 15
    fi
done

0 个答案:

没有答案