说明:蓝色=命令名称
浅绿=命令参数
浅蓝=选项
紫色=目录
系统环境:CentOS 5.8 x86_64
朋友让帮谢了一个生成报表的shell,感觉很有意思发出来大家讨论讨论。
总共三个文件如下图:
iplist
- #group1
- 192.168.1.1
- 192.168.1.2
- #group2
- 192.168.1.3
- 192.168.1.4
myreport.sh
- #!/bin/bash
- vmstat 1 2|awk '{cpuidel=$(NF-2);iowait=$(NF-1)}END{printf("cpuidel=%s iowait=%s",cpuidel,iowait)}'
- awk '{printf " loadavg="$1}' /proc/loadavg
- awk -F"[ :]+" 'NR==5{printf " swap="$2/1024}' /proc/meminfo
- netstat -an|awk '/^tcp/{a[$6]++}END{printf " max_conn="a["ESTABLISHED"]}'
- printf "\n"
report.sh
- #!/bin/bash
- export PATH=/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/usr/local/php/bin:/root/bin:/home/tangweizhong/shell/bin
- DATE=`date +%F`
- MONTH=`date +%m`
- YEAR=`date +%Y`
- rm -f system-report-$DATE.html
- for ip in `awk 'BEGIN{RS="#";FS="\n"}NR>1{i=1;while(++i<NF)print $1"="$i}' iplist`
- do
- printf "%s " ${ip%=*}
- printf "%s " ${ip#*=}
- sh myreport.sh
- done |awk '
- BEGIN{
- warn["max_conn"]=2
- warn["swap"]=5
- FS="[ =]"
- }
- {
- a[$1,NR,"ip"]=$2
- b[$1,"1"]="ip"
- c[$1]
- for(i=3;i<NF;i++){
- j=i
- b[$1,i]=$i
- a[$1,NR,$j]=$(++i)
- }
- }
- END{
- step=1
- print "<html>"
- print "<body>"
- for(group in c){
- print "<h1>"group" SYSTEM REPORT</h1>"
- step+=(NR/length(c))
- print "<table>"
- for(i=1;i<NF;ii=i+2){
- print "<tr>"
- print "<td Bgcolor=#FFCC33 align=right >"b[group,i]"</td>"
- for(j=step-NR/length(c);j<step;j++){
- if(warn[b[group,i]]>0&&a[group,j,b[group,i]]>warn[b[group,i]]){
- print "<td Bgcolor=red align=right>"a[group,j,b[group,i]]"</td>"
- }else{
- print "<td Bgcolor=#CCFFFF align=right>"a[group,j,b[group,i]]"</td>"
- }
- }
- print "</tr>"
- }
- print "</table>"
- }
- print "</body>"
- print "</html>"
- }' >> system-report-$DATE.html
效果如图:
结束语:脚本是我随便写的,这里只是感觉这个思路不错,以前都是用python,没有想过shell也可以做到。根据这个思路可以自己定义各种表表,效果更加直观,比光看数据好多了。
补充:
- awk '/CPU.*idle/{
- while(1){
- getline;
- if($NF){
- idle=$6>idle?$NF:idle;
- iowait=$5>iowait?$5:iowait
- }else
- break
- }
- }/run/{
- while(1){
- getline;
- if($0!=""&&NR!=a){
- loadavg=$NF>loadavg?$NF:loadavg
- }else{
- break
- }
- ;a=NR
- }
- }/IFACE.*rxmcst/{
- while(1){
- getline;
- if($0!=""){
- rxbyt=$5>rxbyt?$5:rxbyt;
- txbyt=$6>txbyt?$6:txbyt}else break
- }
- }/kbmemfree/{
- while(1){
- getline;if($0!=""){
- swap=$9>swap?$9:swap
- }else
- break
- }
- }END{
- printf("idle=%s iowait=%s loadavg=%s rxbyt=%s txbyt=%s swap=%s\n",idle,iowait,loadavg,rxbyt,txbyt,swap)
- }' 报表文件
本脚本用来分析sar 报表,可配合上面脚本数据源。
效果图: