云计算百科
云计算领域专业知识百科平台

消耗Linux(Centos7)服务器cpu、内存和磁盘方法

一、CPU使用率

1、脚本准备

1)创建shell脚本文件:

cd /opt

vim cpu.sh

2)输入以下脚本内容:

#!/bin/bash

FILE_NAME=`basename $0`

cpunum=$2

pid_array=()

function usage()

{

echo "Usage:$FILE_NAME consume cpu_number|release —–the value of cpu_number is an integer,such as 1,2,3"

echo "Example: $FILE_NAME consume 12"

echo "         $FILE_NAME release"

}

function endless_loop()

{

echo -ne "i=0;

while true

do

    i=i+100;

    i=100

done" | /bin/bash &

}

function consume()

{

for i in `seq $1`

do

    endless_loop

    pid_array[$i]=$!

done

echo "consume cpu resources process ids are: ${pid_array[*]}"

}

 function release()

{

for pid in $(ps -ef |grep /bin/bash |grep -v grep |awk '{print $2}' |xargs)

do

    kill -9 $pid

done

}

 function main()

{

case "$1" in

    consume) consume $cpunum;;

    release) release;;

          *) usage;exit 1;;

esac

}

main $*

2、运行脚本 保存文件,运行此shell脚本

sh cpu.sh consume 所需要占用的cpu核数

注意:在运行该脚本时,需要先确认当前服务器的cpu核数之后在运行,以免出现CPU使用率太高导致服务器宕机。

例如当前服务器的配置为8核16G,需要将服务器的cpu使用率提高至10%-20%,你需要使用该脚本运行占用1核CPU,以达到服务器CPU资源使用率达到10%左右的目的,此时运行命令为:

sh cpu.sh consume 1

3、可使用 top 命令查看cpu运行是否达标

https://www.wsisp.com/helps/wp-content/uploads/2025/06/20250610080048-6847e63058c35.png

3、资源回收:资源释放命令

sh cpu.sh release

二、内存使用率 1、脚本准备 1)创建脚本文件:

cd /opt

vim memory.sh

2)输入以下脚本内容:

#!/bin/bash
FILE_NAME=`basename $0`
memsize=$2
function usage()
{
echo "Usage:$FILE_NAME consume memory_size|release —–the value of memory_size like 100M 2G and etc"
echo "Example: $FILE_NAME consume 1G"
echo " $FILE_NAME release"
}
function consume()
{
if [ -d /tmp/memory ];then
echo "/tmp/memory already exists"
else
mkdir /tmp/memory
fi
mount -t tmpfs -o size=$1 tmpfs /tmp/memory
dd if=/dev/zero of=/tmp/memory/block

}
function release()
{
rm /tmp/memory/block;ret=$?
if [ $ret != 0 ]; then
echo "remove memory data failed"
return $ret
fi
umount /tmp/memory;ret=$?
if [ $ret != 0 ]; then
echo "umount memory filedir failed"
return $ret
fi
rmdir /tmp/memory;ret=$?
if [ $ret != 0 ]; then
echo "remove memory filedir failed"
return $ret
fi
}
function main()
{
case "$1" in
consume) consume $memsize;;
release) release;;
*) usage;exit 1;;
esac
}
main $*

2、脚本运行 保存文件,运行此shell脚本

sh memory.sh consume 所需要占用的内存

注意:在运行该脚本时,需要先确认当前服务器的内存大小之后再运行,以免出现内存使用率太高导致服务器宕机。

例如当前服务器的配置为816G,需要将服务器的内存使用率提高至10%-20%,则运行占用5G,以达到服务器内存资源使用率达到10%左右的目的,此时运行命令为:

sh memory.sh consume 1G

3、资源回收:资源释放命令

sh memory.sh release

三、在磁盘中写入相应大小的文件:

—-创建文件11G dd if=/dev/zero of=test1.txt count=10 bs=1024M —-创建文件16G dd if=/dev/zero of=test2.txt count=15 bs=1024M —-创建文件25G dd if=/dev/zero of=test1.txt count=23 bs=1024M —-创建文件129G dd if=/dev/zero of=test9.txt count=60 bs=2048M —-创建文件168G  dd if=/dev/zero of=test1.txt count=80 bs=2000M —-创建文件258G dd if=/dev/zero of=test11.txt count=120 bs=2048M —-创建文件275G dd if=/dev/zero of=test10.txt count=128 bs=2048M

赞(0)
未经允许不得转载:网硕互联帮助中心 » 消耗Linux(Centos7)服务器cpu、内存和磁盘方法
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!