您的位置:首页 > 运维架构 > Shell

linux 性能数据采集bash脚本

2016-07-22 17:38 399 查看
本来打算用zabbix来收集性能数据,但在生产环境中不能装zabbix_agent,所以改用shell脚本和操作系统自带的命令来类似的功能。用到的操作系统命令包括vmstat、uptime、free、iostat和ps,采集到的数据保存到文件,一天一个文件。

1.系统整体性能

os_monitor.sh

#!/bin/bash

os_logfile=$(date "+%Y%m%d")
os_logfile=os_${os_logfile}.log
LOG_HOME=/home/oliver/testing/log
rec_time=$(date "+%Y%m%d-%H:%M:%S")
uptime |awk 'BEGIN{a="'${rec_time}' uptime"}{printf("%s\t%s\n",a,$0)}' >> ${LOG_HOME}/${os_logfile}
vmstat |awk 'NR==3{print}' |awk 'BEGIN{a="'${rec_time}' vmstat"}{printf("%s\t%s\n",a,$0)}'  >> ${LOG_HOME}/${os_logfile}
free -m |grep Mem |awk '{$1="'${rec_time}' free";print $0}'  >> ${LOG_HOME}/${os_logfile}
iostat -x |awk '{if(NR==4)print}' |awk 'BEGIN{a="'${rec_time}' iostat-cpu"}{printf("%s\t%s\n",a,$0)}'  >> ${LOG_HOME}/${os_logfile}
iostat -x |awk '{if(NR>6 && NF>0)print}' |awk 'BEGIN{a="'${rec_time}' iostat-io"}{printf("%s\t%s\n",a,$0)}'  >> ${LOG_HOME}/${os_logfile}
说明

date 取日期和时间

uptime的输出如下,通过awk 增加一列包含uptime 和时间,这样所有的记录写到一个文件就能够区分了。

oliver@bigdatadev:~/_src/shell/monitor$ uptime
16:42:14 up  8:03,  4 users,  load average: 0.00, 0.02, 0.05
oliver@bigdatadev:~/_src/shell/monitor$


oliver@bigdatadev:~/_src/shell/monitor$ uptime |awk 'BEGIN{a="'${rec_time}' uptime"}{printf("%s\t%s\n",a,$0)}'
20160722-16:44:38 uptime	 16:44:39 up  8:06,  4 users,  load average: 0.22, 0.06, 0.06
oliver@bigdatadev:~/_src/shell/monitor$


vmstat的处理方法类似

oliver@bigdatadev:~/_src/shell/monitor$ vmstat
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
0  0      0 2553036 119792 726224    0    0    25     7   67  198  1  0 98  0  0
oliver@bigdatadev:~/_src/shell/monitor$
第一个awk取第3行,第二个awk增加列

oliver@bigdatadev:~/_src/shell/monitor$ rec_time=$(date "+%Y%m%d-%H:%M:%S")
oliver@bigdatadev:~/_src/shell/monitor$ vmstat |awk 'NR==3{print}' |awk 'BEGIN{a="'${rec_time}' vmstat"}{printf("%s\t%s\n",a,$0)}'
20160722-16:47:34 vmstat	 1  0      0 2552260 119808 726228    0    0    25     7   67  198  1  0 98  0  0
oliver@bigdatadev:~/_src/shell/monitor$

free和iostat是类似的处理方法

2.进程性能

proc_monitor.sh

#!/bin/bash

proc_logfile=$(date "+%Y%m%d")
proc_logfile=proc_${proc_logfile}.log
echo $proc_logfile
rec_time=$(date "+%Y%m%d-%H:%M:%S")
ps -eo user,pid,%cpu,%mem,vsz,rss,start,stat,time,pri,command --sort user,command | grep oliver | awk '{$1="'${rec_time}'";print $0}' >> /home/oliver/te
sting/log/${proc_logfile}


3. crontab

crontab -e

* * * * * /home/oliver/testing/proc_monitor.sh

每分钟收集一次数据,保持到文件。

后续再用脚本分析和画图。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: