Linux 'mpstat' 在 crontab 脚本中无法按预期工作



我有一个从根 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 bitskernel-2.6.18-371.el5

我知道

这有点旧了,但我今天刚遇到这个。 正如您所指出的,采购.bash_profile解决了问题。 在手册页中,我找到了这句话:

环境 mpstat 命令考虑了以下环境变量:

  S_TIME_FORMAT
         If  this variable exists and its value is ISO then the current locale will be ignored when printing the date in the report header.
         The mpstat command will use the ISO 8601 format (YYYY-MM-DD) instead.

对我来说,主要区别在于 12 小时制与 24 小时制,因此需要 4,6 美元对 3,5 美元。

您需要使用:

mpstat 1 1

这里解释了原因:带有参数的mpstat这将只给你 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 "ServertDatettt%%usrt%%nicet%%syst%%iowaitt%%irqt%%softt%%stealt%%guestt%%gnicet%%idlen" > $FN
fi
DATE=$(date +'%Y-%m-%d %H:%M:%S')
SERVER="Jupyter"
STAT=$(mpstat 1 1 | awk 'NR==4{printf "%.2ft%.2ft%.2ft%.2ft%.2ft%.2ft%.2ft%.2ft%.2ft%.2ft", $4, $5, $6, $7, $8, $9, $10, $11, $12, $13}')
echo -e "$SERVERt$DATEt$STAT" >> $FN

相关内容

  • 没有找到相关文章

最新更新