shell实现对cpu、mem、disk、网速的各个指标进行监控

今天正在公司歇着,突然被提了个需求:将CPU的各项指标参数化,查询,哪还等什么呢?开整......:

摸索一:

# CPU0: 0.0% usr 54.5% sys 0.0% nic 45.4% idle 0.0% io 0.0% irq 0.0% sirq
# CPU1: 0.0% usr 0.0% sys 0.0% nic 100% idle 0.0% io 0.0% irq 0.0% sirq


#!/bin/sh
top -n 1 <<EOF >test_cpu.log
c
EOF
sed -e 's/[[:space:]][[:space:]]*/ /g' test_cpu.log >Processed.txt
cpu0_use=$(find Processed.txt |xargs grep 'CPU0:'|cut -d ' ' -f 2)
# echo "========================cpu0_use: $cpu0_use========================"
cpu1_use=$(find Processed.txt |xargs grep 'CPU1:'|cut -d ' ' -f 2)
# echo "========================cpu1_use: $cpu1_use========================"


cpu0_sys=$(find Processed.txt |xargs grep 'CPU0:'|cut -d ' ' -f 6)
# echo "========================cpu0_sys: $cpu0_sys========================"
cpu1_sys=$(find Processed.txt |xargs grep 'CPU1:'|cut -d ' ' -f 6)
# echo "========================cpu1_sys: $cpu0_sys========================"


cpu0_user=$(find Processed.txt |xargs grep 'CPU0:'|cut -d ' ' -f 4)
# echo "========================cpu0_user: $cpu0_user========================"
cpu1_user=$(find Processed.txt |xargs grep 'CPU1:'|cut -d ' ' -f 4)
# echo "========================cpu1_user: $cpu0_user========================"


cpu0_idle=$(find Processed.txt |xargs grep 'CPU0:'|cut -d ' ' -f 10)
# echo "========================cpu0_idle: $cpu0_idle========================"
cpu1_idle=$(find Processed.txt |xargs grep 'CPU1:'|cut -d ' ' -f 10)
# echo "========================cpu1_idle: $cpu0_idle========================"


cpu0_iowait=$(find Processed.txt |xargs grep 'CPU0:'|cut -d ' ' -f 12)
# echo "========================cpu0_iowait: $cpu0_iowait========================"
cpu1_iowait=$(find Processed.txt |xargs grep 'CPU1:'|cut -d ' ' -f 12)
# echo "========================cpu1_iowait: $cpu0_iowait========================"


if [ -n "$1" ];then

    case "$1" in
        cpu0_use) echo "========================cpu0_use: $cpu0_use========================";;
        cpu1_use) echo "========================cpu1_use: $cpu1_use========================";;
        cpu0_sys) echo "========================cpu0_sys: $cpu0_sys========================";;
        cpu1_sys) echo "========================cpu1_sys: $cpu1_sys========================";;
        cpu0_user) echo "========================cpu0_user: $cpu0_user========================";;
        cpu1_user) echo "========================cpu1_user: $cpu1_user========================";;
        cpu0_idle) echo "========================cpu0_idle: $cpu0_idle========================";;
        cpu1_idle) echo "========================cpu1_idle: $cpu1_idle========================";;
        cpu0_iowait) echo "========================cpu0_iowait: $cpu0_iowait========================";;
        cpu1_iowait) echo "========================cpu1_iowait: $cpu1_iowait========================";;
       
                 
        
    esac
fi        

 注意:sed -e 's/[[:space:]][[:space:]]*/ /g' test_cpu.log 这个命令可以将.log文件中的空格去掉。

摸索二:

#!/bin/sh
mpstat -P ALL 2 3 |grep '^Average' >tmp.log
    case "$2" in 
        cpu_usr)
            awk -v t="$1" '{if($2==t) {print $3}}' tmp.log;;
        cpu_sys)
            awk -v t="$1" '{if($2==t) {print $5}}' tmp.log;;
        cpu_idle)
            awk -v t="$1" '{if($2==t) {print $11}}' tmp.log;;
        cpu_use)
            awk '/all/{print 100-$NF}' tmp.log;;
    esac
rm -f tmp.log

 ==================================================================================================================================================================

通过自己对这个业务的熟悉优化了相关脚本:get_args.sh + get_net_speed.sh

# get_net_speed.sh
#!/bin/sh ethn=$1 function get_net_speed { RX_pre=$(cat /proc/net/dev | grep $ethn | sed 's/:/ /g' | awk '{print $2}') TX_pre=$(cat /proc/net/dev | grep $ethn | sed 's/:/ /g' | awk '{print $10}') sleep 1 RX_next=$(cat /proc/net/dev | grep $ethn | sed 's/:/ /g' | awk '{print $2}') TX_next=$(cat /proc/net/dev | grep $ethn | sed 's/:/ /g' | awk '{print $10}') clear RX=$((${RX_next}-${RX_pre})) TX=$((${TX_next}-${TX_pre})) if [[ $RX -lt 1024 ]];then RX="${RX}B/s" elif [[ $RX -gt 1048576 ]];then RX=$(echo $RX | awk '{print $1/1048576 "MB/s"}') else RX=$(echo $RX | awk '{print $1/1024 "KB/s"}') fi if [[ $TX -lt 1024 ]];then TX="${TX}B/s" elif [[ $TX -gt 1048576 ]];then TX=$(echo $TX | awk '{print $1/1048576 "MB/s"}') else TX=$(echo $TX | awk '{print $1/1024 "KB/s"}') fi echo "*************************************" echo -e "\033[32m Current net_card: $ethn \033[0m" echo -e "\033[32m upload: \033[0m $TX" echo -e "\033[32m download: \033[0m $RX" echo "*************************************" } get_net_speed
# get_args.sh

#!/bin/sh

: '
脚本get_args.sh在执行的时候需要根据不同的查询需求,需要进行传参
    例如:
        ./get_args.sh mem MemFree
        ./get_args.sh cpu 0 cpu_usr
        ./get_args.sh disk dd
        ./get_args.sh net_speed

'


function mem_info()
{
  # ^$1: 代表第一个参数为首
  echo "mem_info要查询的参数如果有需要,请执行:cat /proc/meminfo,确定好自己要查询的参数!"
  grep "^$1:" /proc/meminfo |awk '{print $2}'
}


function cpu_info()
{
  echo "mem_info要查询的主要参数有:cpu_usr、cpu_sys、cpu_idle、cpu_use"
  mpstat -P $1 2 3 |grep '^Average' >tmp.log
    case "$2" in
        cpu_usr)
            awk -v t="$1" '{if($2==t) {print $3}}' tmp.log;;
        cpu_sys)
            awk -v t="$1" '{if($2==t) {print $5}}' tmp.log;;
        cpu_idle)
            awk -v t="$1" '{if($2==t) {print $11}}' tmp.log;;
        cpu_use)
            awk '/all/{print 100-$NF}' tmp.log;;
    esac
 rm -f tmp.log
        
}

function kill_demo()
{
    pid=$( ps -ef|egrep 'dd if' | grep -v 'grep'| awk '{print $1}')
    [ -n "$pid" ] && kill -2 $pid
    kill -9 $pid  &>/dev/null # 如果kill -2 不能结束用kill -9 结束

}


function disk_info() 
{
    source_path="/root/sd/p3/test_file/"
    [ ! -d source_path ] && mkdir -p $source_path
    cd $source_path
    [ -f disk_stats.log ] && rm -f disk_stats.log && rm -f template
    # 这里传参看是否进行传参进行dd [dd if=/dev/zero of=template bs=1M count=1024]
    [ "$1" = "dd" ] && dd if=/dev/zero of=template bs=1M count=1024 &
    Used=$(df -h |grep /dev/mmcblk2p3|awk '{print $5}'|sed 's/\%//g')
    while [ $Used -lt 9 ]
            do
                    echo "Current time: $(date +'%Y-%m-%d %H:%M:%S')"|tee -a disk_stats.log
                    Used=$(df -h |grep /dev/mmcblk2p3|awk '{print $5}'|sed 's/\%//g')
                    echo "Used: $Used" |tee -a disk_stats.log
                    sleep 3
                    [ $Used -ge 9 ] && echo "Warning: Disk_use has triggered the alarm,it will be killed and deleted!!!"|tee -a disk_stats.log && kill_demo && rm -f template && break
            done
        
}

function net_speed()
{
    [ -f net_speed.log ] && rm -f net_speed.log
    read -p "Please provide the program running time[Unit: seconds]:" runtime
    start_time=$(date +%s)
    end_time=$((start_time + runtime))

    while [ $(date +%s) -lt $end_time ] 
    do
        echo "Current time: $(date +'%Y-%m-%d %H:%M:%S')"|tee -a net_speed.log 
        sleep 5
        ./get_net_speed.sh eth0|tee -a net_speed.log
    done

}


case $1 in
     "mem")
           mem_info $2;;
     "cpu")
           cpu_info $2 $3;;
     "net_speed")
           net_speed;;  
     "disk")
           disk_info $2;;   
     *)
          echo "error args..."
esac

通过这段时间脚本的编写,也学习了不少知识点:

1)case的灵活应用,case传参只考虑传参位置即可;

2)边打印边追加至log的写法 cat xxx |tee -a $i/xx.log ;

3)awk的灵活取参;

4)有关dd:

a.会写缓存 

# # 纯写
# time dd if=/dev/zero of=template bs=1M count=1024
# # 纯读
# time dd if=template of=/dev/null bs=1M count=1024

b.测试纯写入性能——相当于不写缓存,直接写裸磁盘(写1G文件)

## 纯写

# time dd if=/dev/zero of=output.file bs=8k count=128000 oflag=direct,nonblock

## 纯读

# dd if=output.file of=/dev/null bs=8k count=128000 iflag=direct,nonblock

 

5)获取当前目录的简洁写法:source_path=$(pwd) ;

6)还有if判断的新写法:[ ! - d/-f $i ] && xxx || xxxx   ;   

7) read -p 的灵活输入参数;

8)shell中的自增 let i++

9)df -h |grep /dev/mmcblk2p3|awk '{print $5}'|sed 's/\%//g' [可以取值的时候去掉%,这里的'%'可以替换成其他符号]

10)$(date +%s) 一定要注意

11)shell的整数/浮点数的 "加减乘除"

echo "scale=1;$Disk_Size*0.98-$Disk_Available" |bc   # scale 控制的是小数点后几位;——>echo "scale=1;100*0.98-10" |bc    

  整数之间的和计算:res=$(($a+$b))

12)shell中的多行注释:

# 多行注释的常用几种方法:

:<< 'BLOCK
....被注释的多行内容
BLOCK'



:<< '
....被注释的多行内容
'



: '
....被注释的多行内容
'

 

 

 

最后,还有一个领导想要全部指标展示的代码:

# get_sys_info.sh

#! /bin/sh
function get_index()
{

 cat << EOF
+---------------------------------------------------------------------------------+
|                           欢迎使用 【系统信息检查脚本】                          |
+---------------------------------------------------------------------------------+
EOF
time=1
source_path=$(pwd)
log_file=$(pwd)/mylog/
[ ! -d $log_file ] && mkdir -p $log_file
cd $log_file
rm -f *.log
read -p "Please input query times:" run_time
length=$(echo ${run_time} | wc -L)
run_time=$(expr $run_time + 1)
while :
do
      if [ $time -ge $run_time ];then
                  echo "ALL operations have been over,exit"
                  exit
          else
                   echo "CPU_info_query Times of executions:"$time
                   echo "===============================================CPU_info_query $(date +'%Y-%m-%d %H:%M:%S') ==================================================="|tee -a $log_file/cpu_info.log
                   mpstat -P ALL 2 3 | grep '^Average'|awk '{printf "%-10s%-10s%-10s%-10s%-10s\n", $2 , $3 , $5 , $6 , $NF}'|tee -a $log_file/cpu_info.log
                   sleep 5   

                   echo "Mem_info_query Times of executions:"$time
                   echo "===============================================Mem_info_query $(date +'%Y-%m-%d %H:%M:%S') ==================================================="|tee -a $log_file/mem_info.log
                   cat /proc/meminfo|head -n 4|sed 's/\://g'|awk '{for(i=0;++i<=NF;)a[i]=a[i]?a[i] FS $i:$i}END{for(i=0;i++<(NF-1);)print a[i]}'|tee -a $log_file/mem_info.log
                   sleep 5
                   
                   echo "Disk_info_query Times of executions:"$time
                   echo "================================================Disk_info_query $(date +'%Y-%m-%d %H:%M:%S') =================================================="|tee -a $log_file/disk_info.log
                   read -p "Please enter the partition you want to query:" zone
                   df -h|grep Filesystem|sed -e 's/[[:space:]][[:space:]]*/ /g'|awk '{printf "%-10s%-10s%-10s%-10s%-10s\n", $2,$3,$4,$5,$6}'|tee -a $log_file/disk_info.log
                   df -h|grep $zone|awk '{printf "%-10s%-10s%-10s%-10s%-10s\n", $2,$3,$4,$5,$6}'|tee -a $log_file/disk_info.log
                   sleep 5
                   
                   echo "Net_speed_query Times of executions:"$time
                    echo "===============================================Net_speed_query $(date +'%Y-%m-%d %H:%M:%S') ==================================================="|tee -a $log_file/net_speed.log
                   cd $source_path
                   ./get_net_speed.sh eth0|tee -a $log_file/net_speed.log
                   sleep 5
              let time++    
      fi
done
}
get_index

  

 

 更新中...【个人觉得后续要更新一下邮件提醒,类似钉钉/飞书提醒】

优化版

 

#!/bin/sh

: '
脚本get_sys_args.sh在执行的时候需要根据不同的查询需求,需要进行传参
    例如:
        ./get_sys_args.sh mem MemFree/...
        ./get_sys_args.sh cpu 0/1/all cpu_usr/...
        ./get_sys_args.sh disk write w_speed/read r_speed
        ./get_sys_args.sh net_speed
        ./get_sys_args.sh Disk_wr
        ./get_sys_args.sh disk_dd dd

'
Log_dir=$(pwd)/log_file
[ ! -d $Log_dir ] && mkdir -p $Log_dir

function mem_info()
{
  # ^$1: 代表第一个参数为首
  echo "mem_info要查询的参数如果有需要,请执行:cat /proc/meminfo,确定好自己要查询的参数!"
  grep "^$1:" /proc/meminfo |awk '{print $2}'
}


function cpu_info()
{
  echo "cpu_info_$1 要查询的主要参数有:cpu_usr、cpu_sys、cpu_idle、cpu_use"
  mpstat -P ALL 2 3 |grep '^Average' >tmp.log
    case "$2" in
        cpu_usr)
            awk -v t="$1" '{if($2==t) {print $3}}' tmp.log;;
        cpu_sys)
            awk -v t="$1" '{if($2==t) {print $5}}' tmp.log;;
        cpu_idle)
            awk -v t="$1" '{if($2==t) {print $11}}' tmp.log;;
        cpu_use)
            awk -v t="$1" '{if($2==t) {print 100-$NF}}' tmp.log;; # 如果传参获取一个值的时候,可以使用但括号:awk -v t="$1" '{if($2==t) print 100-$NF}' tmp.log;;

    esac
 rm -f tmp.log
        
}

function kill_demo()
{
    pid=$( ps -ef|egrep 'dd if' | grep -v 'grep'| awk '{print $1}')
    [ -n "$pid" ] && kill -2 $pid
    kill -9 $pid  &>/dev/null # 如果kill -2 不能结束用kill -9 结束

}


function disk_info() 
{
   # echo $@ 查询函数传参的详情
    
    journal=$Log_dir/disk_journal
    [ ! -d $journal ] && mkdir -p $journal || [ -f $journal/*.log ] && rm -f $journal/*.log

    Disk_Size=$(df -h |grep /dev/mmcblk2p3|awk '{print $2}'|sed 's/\G//g')
    Disk_Available=$(df -h |grep /dev/mmcblk2p3|awk '{print $4}'|sed 's/\G//g')
    Used=$(df -h |grep /dev/mmcblk2p3|awk '{print $5}'|sed 's/\%//g') 
    Warning_limit=$(echo "scale=0;$Disk_Size*0.1" |bc)

    if [ "$1" = "write" ]; then
        echo "The current disk status:Disk_Size: $Disk_Size  | Disk_Available: $Disk_Available | Used %: $Used"
        while [ `echo "$Disk_Available > 0" | bc` -eq 1 ]
        do
            [ "$2" = "w_speed" ] && echo "Please wait for writing..." || exit  
            
            [ `echo "$Disk_Available < $Warning_limit" | bc` -eq 1 ] && exit || dd if=/dev/zero of=template bs=1M count=12288 2>$journal/write_speed.log
            w_speed=$(cat $journal/write_speed.log |grep 'seconds,'|awk '{print $NF}')
            echo "w_speed:" $w_speed 
        done
    elif [ "$1"="read" ]; then
        [ "$2" = "r_speed" ] && echo "Please wait for reading" || exit  
        [ -f template  ] && dd if=template of=/dev/null bs=1M count=12288 2>$journal/read_speed.log || echo "The file is not existed" 
        r_speed=$(cat $journal/read_speed.log|grep 'seconds,'|awk '{print $NF}' )
        echo "r_speed:" $r_speed
    fi
}

function disk_dd()
{
    # 可以添加一个功能询问在哪个分区进行dd
    journal=$Log_dir/dd_journal
    [ ! -d $journal ] && mkdir -p $journal || [ -f $journal/disk_stats.log ] && rm -f $journal/disk_stats.log

    [ "$1" = "dd" ] && dd if=/dev/zero of=template bs=1M count=1024 & 
    while true
        do
            echo "Current time: $(date +'%Y-%m-%d %H:%M:%S')"|tee -a $journal/disk_stats.log
            Used=$(df -h |grep /dev/mmcblk2p3|awk '{print $5}'|sed 's/\%//g') 
            [ $Used -ge 9 ] && echo "Warning:Disk_use has exceeded the alarm,it will be deleted!!!" && kill_demo && rm -f template && break || echo "Used: $Used" |tee -a $journal/disk_stats.log
            sleep 5
        done
}

function Disk_wr(){

    [ ! -f read_write_test.sh ] && wget http://xxx/scripts/read_write_Test/read_write_test.sh && chmod +x read_write_test.sh

   # 如果这里需要对准备的数据做限制,这里需要优化
          ./read_write_test.sh source/ target 10


} : ' # wget_loop.sh [调用该函数,再启动另一个窗口进行执行该脚本] #!/bin/sh [ -z $1 ] && loop_time=100 || loop_time=1 for i in $(seq 1 $loop_time) do echo "==== 当前第 $i 次测试 ======" wget http://xxx:port/k510_images/v1.9-ed9472d-20230130-122418CST-root-AITestGroup/sysimage-emmc.img sleep 2 rm -f sysimage-emmc.img sleep 60 done ' function net_speed() { journal=$Log_dir/net_journal [ ! -d $journal ] && mkdir -p $journal || [ -f $journal/net_speed.log ] && rm -f $journal/net_speed.log read -p "Please provide the program running time[Unit: seconds]:" runtime start_time=$(date +%s) end_time=$((start_time + runtime)) while [ $(date +%s) -lt $end_time ] do echo "Current time: $(date +'%Y-%m-%d %H:%M:%S')"|tee -a $journal/net_speed.log sleep 5 [ -f get_net_speed.sh ] && ./get_net_speed.sh eth0|tee -a $journal/net_speed.log || echo "Please check your Script!" done } function send_report() { echo "PASS" } case $1 in "mem") mem_info $2;; "cpu") cpu_info $2 $3;; "net_speed") net_speed;; "disk") disk_info $2 $3;; "Disk_wr") Disk_wr;; "disk_dd") disk_dd $2;; *) echo "error args..." esac

 

  当然在disk_dd这里如果需要写成传参查看指定分区代码如下:

#!/bin/sh
function disk_dd()
{
    # 可以添加一个功能询问在哪个分区进行dd
    journal=$Log_dir/dd_journal
    [ ! -d $journal ] && mkdir -p $journal || [ -f $journal/disk_stats.log ] && rm -f $journal/disk_stats.log
    
    [ "$1" = "dd" ] && read -p "Please enter the partition you want to query:" zone
    dd_path=$(df -h |grep $zone|awk '{print $NF}') 
    dd if=/dev/zero of=$dd_path/template bs=1M count=1024 & 
    while true
        do
            echo "Current time: $(date +'%Y-%m-%d %H:%M:%S')"|tee -a $journal/disk_stats.log
            Used=$(df -h |grep $zone|awk '{print $5}'|sed 's/\%//g') 
            [ $Used -ge 9 ] && echo "Warning:Disk_use has exceeded the alarm,it will be deleted!!!" && kill_demo && rm -f template && break || echo "Used: $Used" |tee -a $journal/disk_stats.log
            sleep 5
        done
}
disk_dd

  

 

 

#get_net_speed.sh

#!/bin/sh

ethn=$1
function get_net_speed {
     RX_pre=$(cat /proc/net/dev | grep $ethn | sed 's/:/ /g' | awk '{print $2}')
     TX_pre=$(cat /proc/net/dev | grep $ethn | sed 's/:/ /g' | awk '{print $10}')
     sleep 1
     RX_next=$(cat /proc/net/dev | grep $ethn | sed 's/:/ /g' | awk '{print $2}')
     TX_next=$(cat /proc/net/dev | grep $ethn | sed 's/:/ /g' | awk '{print $10}')

     clear
     RX=$((${RX_next}-${RX_pre}))
     TX=$((${TX_next}-${TX_pre}))

     if [[ $RX -lt 1024 ]];then
     RX="${RX}B/s"
     elif [[ $RX -gt 1048576 ]];then
     RX=$(echo $RX | awk '{print $1/1048576 "MB/s"}')
     else
     RX=$(echo $RX | awk '{print $1/1024 "KB/s"}')
     fi

     if [[ $TX -lt 1024 ]];then
     TX="${TX}B/s"
     elif [[ $TX -gt 1048576 ]];then
     TX=$(echo $TX | awk '{print $1/1048576 "MB/s"}')
     else
     TX=$(echo $TX | awk '{print $1/1024 "KB/s"}')
     fi
     echo "*************************************"
     echo -e "\033[32m Current net_card:  $ethn \033[0m"
     echo -e "\033[32m upload: \033[0m $TX"
     echo -e "\033[32m download: \033[0m $RX"
     echo "*************************************"

}

get_net_speed

 

# write_read_test.sh


#!/bin/sh ######################################################################################################################## # # 读写文件支持两种方式,直接cp或者用dd 对比文件有两种方式,用cmp或者对比md5值 # 读写测试: # 1. 把需要测试的文件放到sd卡或emmc上,文件可以在这里下载http://10.1x.1.xx:60000/test_use_files/testDownload/ # 2. 执行当前脚本 # ######################################################################################################################## source_dir='/root/sd/p3/source_data' target_dir='/root/sd/p3/target_data' [ -z "$1" ] && loop_time=100 || loop_time=$1 # 测试次数 [ -n "$2" ] && mode=$2 || mode='cp' [ ! -d $target_dir ] && mkdir -p $target_dir function msg_red() { echo -e "\033[31m $1 \033[0m" } function msg_green() { echo -e "\033[32m $1 \033[0m" } function msg_blue() { echo -e "\033[34m $1 \033[0m" } function do_test_use_MD5() { cd $source_dir for file_to_test in * do s_md5=$(echo $file_to_test|awk -F '[-.]' '{print $2}' | tr '[a-z]' '[A-Z]' ) # 拿出原文件md5 #echo "file_size_info=$(ls -lh $file_to_test | awk '{print $5}')" file_size_info=$(ls -lh $file_to_test | awk '{print $5}') file_size_number=${file_size_info:0:-1} file_size_unit=${file_size_info: -1} # 单位为G的,转换为M [ $file_size_unit = "G" ] && { file_size_unit='M'; file_size_number=$( echo "$file_size_number * 1024" | bc ) ; } start_time=$(date +%"s") if [ "$mode" = "cp" ]; then echo -n "cp $file_to_test to $target_dir ....." cp $file_to_test $target_dir && sync || echo "cp $file_to_test failed!" echo 3 > /proc/sys/vm/drop_caches &>/dev/null end_time=$(date +%"s") d_md5=$(md5sum $target_dir/$file_to_test |awk '{print $1}'| tr '[a-z]' '[A-Z]') [ $s_md5 = $d_md5 ] && echo -n " cp successed!" || echo "md5sum not match ($s_md5, $d_md5), cp failed!" fi if [ $mode = 'dd' ]; then echo -n "dd $file_to_test to $target_dir ....." dd if=$file_to_test of=$target_dir/$file_to_test conv=fsync && sync || echo "dd $file_to_test failed!" echo 3 > /proc/sys/vm/drop_caches &>/dev/null end_time=$(date +%"s") d_md5=$(md5sum $target_dir/$file_to_test |awk '{print $1}'|tr '[a-z]' '[A-Z]') [ $s_md5 = $d_md5 ] && echo -n "dd successed!" || echo "md5sum not match ($s_md5, $d_md5), dd failed!" fi duration=$((end_time - start_time)) [ $duration -eq 0 ] && duration=1 #echo "$file_size_number / $duration" speed=$(echo "scale=2; $file_size_number / $duration" | bc ) echo "speed = $speed $file_size_unit/s" rm -f $target_dir/$file_to_test done } function do_test() { [ -n "$1" ] && test_time=$1 || test_time=10 # 每个文件测试多少次,默认10次 cd $source_dir for file_to_test in * do #s_md5=$(echo $file_to_test|awk -F '[-.]' '{print $2}' | tr '[a-z]' '[A-Z]' ) # 拿出原文件md5 #echo "file_size_info=$(ls -lh $file_to_test | awk '{print $5}')" test_total=0 test_pass=0 test_fail=0 file_size_info=$(ls -lh $file_to_test | awk '{print $5}') file_size_number=${file_size_info:0:-1} file_size_unit=${file_size_info: -1} # 单位为G的,转换为M [ $file_size_unit = "G" ] && { file_size_unit='M'; file_size_number=$( echo "$file_size_number * 1024" | bc ) ; } for i in $(seq 1 $test_time) do start_time=$(date +%"s") if [ "$mode" = "cp" ]; then echo -n "当前第$i次测试: cp $file_to_test ....." cp $file_to_test $target_dir && sync sync echo 1 > /proc/sys/vm/drop_caches &>/dev/null end_time=$(date +%"s") fi if [ $mode = 'dd' ]; then echo -n "当前第$i次测试: dd $file_to_test ....." dd if=$file_to_test of=$target_dir/$file_to_test conv=fsync && sync sync echo 3 > /proc/sys/vm/drop_caches &>/dev/null end_time=$(date +%"s") fi duration=$((end_time - start_time)) [ $duration -eq 0 ] && duration=1 speed=$(echo "scale=2; $file_size_number / $duration" | bc ) echo -n "speed = $speed $file_size_unit/s" result=$(cmp $file_to_test $target_dir/$file_to_test) if [ $? -eq 0 ]; then msg_green " SUCCESSED! " test_pass=$((test_pass+1)) else msg_red "FAILED! -> $result " test_fail=$((test_fail+1)) fi test_total=$((test_total+1)) rm -f $target_dir/$file_to_test && sync sync echo 3 > /proc/sys/vm/drop_caches &>/dev/null done msg_blue "====== $file_to_test 一共测试$test_total次,成功$test_pass次,失败$test_fail次 ======" done } #for i in $(seq(1 $loop_time)) for t in $(seq 1 $loop_time) do echo ">>>>>>>>>>>>>>>>>> 当前第 $t 轮测试 <<<<<<<<<<<<<<<<<<<<<<<<<<<<" do_test 10 done

  

posted @ 2023-03-13 20:58  弹弹大魔王  阅读(130)  评论(0编辑  收藏  举报