我有一个从root crontab运行的脚本:
05 * * * * /bin/bash /root/systat_kpi_tools/systat_kpi.sh
该脚本的格式为mpstat
,并以CSV格式保存在文件中:
[[ -e ${BASE_DIR}/cpu_stat_${NOW}.csv ]] || echo "Year,Month,Day,Hr,Min,Sec,%user,%nice,%sys,%iowait,%irq,%soft,%steal,%idle,intr/s" >> ${BASE_DIR}/cpu_stat_${NOW}.csv
mpstat | awk 'NR>3{ print substr($0, index($0,$4)) }' | awk -v dt=$(date +'%Y,%m,%d,%H,%M,%S') -v OFS=, '{$1=dt OFS $1; print}' >> ${BASE_DIR}/cpu_stat_${NOW}.csv
文件输出:
# cat cpu_stat_160526.csv
Year,Month,Day,Hr,Min,Sec,%user,%nice,%sys,%iowait,%irq,%soft,%steal,%idle,intr/s
2016,05,26,14,05,01,0.00,2.17,0.08,0.01,0.14,0.00,90.29,1093.83
2016,05,26,15,05,02,0.00,2.19,0.08,0.01,0.14,0.00,90.25,1093.82
当我从脚本中运行命令时:
# echo "Year,Month,Day,Hr,Min,Sec,%user,%nice,%sys,%iowait,%irq,%soft,%steal,%idle,intr/s" > tmp
# mpstat | awk 'NR>3{ print substr($0, index($0,$4)) }' | awk -v dt=$(date +'%Y,%m,%d,%H,%M,%S') -v OFS=, '{$1=dt OFS $1; print}' >> tmp
# mpstat | awk 'NR>3{ print substr($0, index($0,$4)) }' | awk -v dt=$(date +'%Y,%m,%d,%H,%M,%S') -v OFS=, '{$1=dt OFS $1; print}' >> tmp
# mpstat | awk 'NR>3{ print substr($0, index($0,$4)) }' | awk -v dt=$(date +'%Y,%m,%d,%H,%M,%S') -v OFS=, '{$1=dt OFS $1; print}' >> tmp
我得到了这个输出:
# cat tmp
Year,Month,Day,Hr,Min,Sec,%user,%nice,%sys,%iowait,%irq,%soft,%steal,%idle,intr/s
2016,05,26,15,04,54,7.33,0.00,2.19,0.08,0.01,0.14,0.00,90.25,1093.82
2016,05,26,15,04,57,7.33,0.00,2.19,0.08,0.01,0.14,0.00,90.25,1093.82
2016,05,26,15,04,58,7.33,0.00,2.19,0.08,0.01,0.14,0.00,90.25,1093.82
当从脚本执行相同的行时,请注意具有值%user
的列7.33,7.33,7.33
,该列从先前的输出中丢失。为什么会出现这种奇怪的行为?
我的Linux风格是RHEL5.10 64 bits
:
kernel-2.6.18-371.el5
答案 0 :(得分:1)
我知道这有点旧,但我今天遇到了这个问题。如你所知,采购.bash_profile解决了这个问题。在手册页中,我找到了这个引用:
环境 mpstat命令考虑以下环境变量:
const myTempVar = this.userRecord; this.form.reset(); this.userRecord = myTempVar;
对我来说,主要的区别是12小时和24小时的时钟,因此需要awk字段$ 4,$ 6 vs $ 3,$ 5。
答案 1 :(得分:0)
您需要使用:
mpstat 1 1
以下说明原因:mpstat with parameters
那只会给你1条线,平均数在底部。然后,您需要解析该行(第4行)。另外,也不需要解析mpstat
给出的日期(或时间),而可以使用$(date +'FORMAT')
获取系统的当前日期。
这是我制作的脚本,它对我有用。如果不存在,它将创建一个文件,然后添加来自mpstat 1 1
的结果。我使用\t
作为分隔符;如果愿意,可以使用,
并将文件扩展名更改为*.csv
。然后,您可以将此脚本添加到crontab中,以每隔x分钟运行一次。
#! /bin/bash
DIR=/somepath
FN=$(date +'CPU-%Y-%m.log')
FN=$DIR/$FN
if [ ! -f $FN ]
then
touch $FN
chmod 644 $FN
printf "Server\tDate\t\t\t%%usr\t%%nice\t%%sys\t%%iowait\t%%irq\t%%soft\t%%steal\t%%guest\t%%gnice\t%%idle\n" > $FN
fi
DATE=$(date +'%Y-%m-%d %H:%M:%S')
SERVER="Jupyter"
STAT=$(mpstat 1 1 | awk 'NR==4{printf "%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t", $4, $5, $6, $7, $8, $9, $10, $11, $12, $13}')
echo -e "$SERVER\t$DATE\t$STAT" >> $FN