因为XMR等利用CPU挖矿软件,对CPU占用率非常高,动不动就100%运行,如果您使用共享VPS,建议避免由矿工产生100%的CPU使用率,否则可能将被禁止使用
所以今天我们需要想办法来限制进程 CPU 使用率,这里就说个教程。
简介
cpulimit 命令的工作原理是为进程预设一个 cpu 占用率上限,并实时监控进程是否超出此上限,而做出动态调整。从而可以控制进程的 cpu 使用率的上限值。
安装
使用 root 运行命令:
#Debian/Ubuntu 系统apt install -y cpulimit#RHEL/Centos/Fedora 系统yum install epel-release cpulimit
参数
cpulimit -h
Usage: cpulimit [OPTiONS...] TARGET
OPTIONS
-l, --limit=N percentage of cpu allowed from 0 to 100 (required)//cpu 限制的百分比
-v, --verbose show control statistics//显示版本号
-z, --lazy exit if there is no target process, or if it dies//如果限制的进程不存在了,则退出。
-i, --include-children limit also the children processes//包括子进程。
-h, --help display this help and exit //帮助,显示参数
TARGET must be exactly one of these:
-p, --pid=N pid of the process (implies -z) //进程的 pid
-e, --exe=FILE name of the executable program file or path name //可执行程序
COMMAND [ARGS] run this command and limit it (implies -z)
举例
#限制 firefox 使用 30% cpu 利用率cpulimit -e firefox -l 30#限制进程号 1313 的程序使用 30%cpu 利用率cpulimit -p 1313 -l 30#限制绝对路径下该软件的 cpu 利用率cpulimit -e /usr/local/Nginx/sbin/nginx -l 50
#!/bin/bashwhile true ; do
id=`ps -ef | grep cpulimit | grep -v "grep" | awk '{print $10}' | tail -1`
nid=`ps aux | awk '{ if ( $3 > 75 ) print $2 }' | head -1`
if [ "${nid}" != "" ] && [ "${nid}" != "${id}" ] ; then cpulimit -p ${nid} -l 75 & echo "[`date`] CpuLimiter run for ${nid} `ps -ef | grep ${nid} | awk '{print $8}' | head -1`" >> /root/cpulimit-log.log
fi
sleep 3
done
保存到 /root/cpulimit.sh,会自动生成日志文件 /root/cpulimit-log.log。
然后修改 /etc/rc.local 在对应位置加入 /root/cpulimit.sh 再重启系统,就会全程限制各个进程的 CPU 使用了!
注意事项
后面限制的 cpu 使用量,要根据实际的核心数量而成倍减少。40%的限制生效在 1 核服务器中,如果是双核服务器,则应该限制到 20%,四核服务器限制到 10%以此类推。
root 用户可以限制所有的进程,普通用户只能限制自己有权限管理的进程。
猫池的脚本
sudo apt-get update; sudo apt-get install -y cpulimit
sudo cpulimit -e xmrig -l 75 -bsudo sed -i -e '$acpulimit -e xmrig -l 75 -b\n' /etc/rc.local
sudo apt-get update; sudo apt-get install -y cpulimit
sudo cpulimit -e xmrig -l 75 -bsudo sed -i -e '$acpulimit -e xmrig -l 75 -b\n' /etc/rc.local
非猫池脚本
同样是安装cpulimit,怎么安装请看上面。
使用 top
命令查看Xmrig运行的pid,假设Pid为2021,那么
cpulimit -p 2021 -l 75
测试
使用 top
命令查看xmrig用户id,可以看到xmrigPID为12013,已经占用了系统93% cpu资源,,几乎占满。

现在我们使用cpulimit,把它限制在20%
运行 cpulimit -p 12013 -l 20
,再看一下占用。

可以看到,xmrig占用已经被控制在20%左右,完全符合我们的要求,完活儿。
上一篇: 使用服务器CPU挖矿的详细新手教程(一):介绍服务器用CPU挖XMR
评论专区