Linux集群和自动化维2.6.2 统计类脚本

    xiaoxiao2024-01-28  160

    2.6.2 统计类脚本

    统计工作一直是Shell和Python脚本的强项,我们完全可以利用sed、awk再加上正则表达式,写出强大的统计脚本来分析我们的系统日志、安全日志及服务器应用日志等。

    1. Nginx负载均衡器日志汇总脚本

    以下脚本是用来分析Nginx负载均衡器的日志的,作为Awstats的补充,它可以快速得出排名最前的网站和IP等,脚本内容如下(此脚本在CentOS 5.8/6.4 x86_64下均已测试通过):

    #!/bin/bash

     

    if [ $# -eq 0 ]; then

       echo "Error: please specify logfile."

       exit 0

    else

       LOG=$1

    fi

     

    if [ ! -f $1 ]; then

       echo "Sorry, sir, I can't find this apache log file, pls try again!"

    exit 0

    fi

     

    ####################################################

    echo "Most of the ip:"

    echo "-------------------------------------------"

    awk '{ print $1 }' $LOG | sort | uniq -c | sort -nr | head -10

    echo

    echo

    ####################################################

    echo "Most of the time:"

    echo "--------------------------------------------"

    awk '{ print $4 }' $LOG | cut -c 14-18 | sort | uniq -c | sort -nr | head -10

    echo

    echo

    ####################################################

    echo "Most of the page:"

    echo "--------------------------------------------"

    awk '{print $11}' $LOG | sed 's/^.*\(.cn*\)\"/\1/g' | sort | uniq -c | sort -rn | head -10

    echo

    echo

    ####################################################

    echo "Most of the time / Most of the ip:"

    echo "--------------------------------------------"

    awk '{ print $4 }' $LOG | cut -c 14-18 | sort -n | uniq -c | sort -nr | head -10 > timelog

     

    for i in `awk '{ print $2 }' timelog`

    do

       num=`grep $i timelog | awk '{ print $1 }'`

       echo " $i $num"

       ip=`grep $i $LOG | awk '{ print $1}' | sort -n | uniq -c | sort -nr | head -10`

       echo "$ip"

       echo

    done

    rm -f timelog

    2. 探测多节点Web服务质量

    工作中有时会出现网络延迟导致程序返回数据不及时的问题,这时就需要精准定位机器是在哪个时间段出现了网络延迟的情况。对此,可以通过Python下的pycurl模块来实现定位,它可以通过调用pycurl提供的方法,来探测Web服务质量,比如了解相应的HTTP状态码、请求延时、HTTP头信息、下载速度等,脚本内容如下所示(此脚本在Amazon Linux AMI x86_64下已测试通过):

    #!/usr/bin/python

    #encoding:utf-8

    #*/30 * * * * /usr/bin/python /root/dnstime.py >> /root/myreport.txt 2>&1

    import os

    import time

    import sys

    import pycurl

    #import commands

    import time

     

    URL="http://imp-east.example.net"

    ISOTIMEFORMAT="%Y-%m-%d %X"

    c = pycurl.Curl()

    c.setopt(pycurl.URL, URL)

    c.setopt(pycurl.CONNECTTIMEOUT, 5)

    c.setopt(pycurl.TIMEOUT, 5)

    c.setopt(pycurl.FORBID_REUSE, 1)

    c.setopt(pycurl.MAXREDIRS, 1)

    c.setopt(pycurl.NOPROGRESS, 1)

    c.setopt(pycurl.DNS_CACHE_TIMEOUT,30)

    indexfile = open(os.path.dirname(os.path.realpath(__file__))+"/content.txt", "wb")

    c.setopt(pycurl.WRITEHEADER, indexfile)

    c.setopt(pycurl.WRITEDATA, indexfile)

    try:

        c.perform()

    except Exception,e:

        print "connecion error:"+str(e)

        indexfile.close()

        c.close()

        sys.exit()

     

    NAMELOOKUP_TIME =  c.getinfo(c.NAMELOOKUP_TIME)

    CONNECT_TIME =  c.getinfo(c.CONNECT_TIME)

    PRETRANSFER_TIME =   c.getinfo(c.PRETRANSFER_TIME)

    STARTTRANSFER_TIME = c.getinfo(c.STARTTRANSFER_TIME)

    TOTAL_TIME = c.getinfo(c.TOTAL_TIME)

    HTTP_CODE =  c.getinfo(c.HTTP_CODE)

    SIZE_DOWNLOAD =  c.getinfo(c.SIZE_DOWNLOAD)

    HEADER_SIZE = c.getinfo(c.HEADER_SIZE)

    SPEED_DOWNLOAD=c.getinfo(c.SPEED_DOWNLOAD)

     

    print "HTTP状态码:%s" %(HTTP_CODE)

    print "DNS解析时间:%.2f ms"%(NAMELOOKUP_TIME*1000)

    print "建立连接时间:%.2f ms" %(CONNECT_TIME*1000)

    print "准备传输时间:%.2f ms" %(PRETRANSFER_TIME*1000)

    print "传输开始时间:%.2f ms" %(STARTTRANSFER_TIME*1000)

    print "传输结束总时间:%.2f ms" %(TOTAL_TIME*1000)

    print "下载数据包大小:%d bytes/s" %(SIZE_DOWNLOAD)

    print "HTTP头部大小:%d byte" %(HEADER_SIZE)

    print "平均下载速度:%d bytes/s" %(SPEED_DOWNLOAD)

     

    indexfile.close()

    c.close()

     

    print time.strftime( ISOTIMEFORMAT, time.gmtime( time.time() ) )

    print "================================================================"

    3.测试局域网内主机是否alive的小脚本

    我们在对局域网的网络情况进行维护时,经常会遇到这样的问题,需要收集网络中存活的IP,这个时候可以写一个Python脚本,自动收集某一网段的IP。现在的IT技术型公司都比较大,网络工程师一般会规划几个VLAN(网段),我们可以用如下这个脚本来收集某个VLAN下存活的主机,(此脚本在CentOS 6.4 x86_64下已测试通过):

    #!/usr/bin/python

    import os

    import re

    import time

    import sys

    import subprocess

     

    lifeline = re.compile(r"(\d) received")

    report = ("No response","Partial Response","Alive")

     

    print time.ctime()

    for host in range(1,254):

       ip = "192.168.1."+str(host)

       pingaling = subprocess.Popen(["ping","-q", "-c 2", "-r", ip], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE)

       print "Testing ",ip,

       while 1:

          pingaling.stdout.flush()

          line = pingaling.stdout.readline()

          if not line: break

          igot = re.findall(lifeline,line)

          if igot:

               print report[int(igot[0])]

    print time.ctime()

    Python对空格的要求是非常严谨的,请大家注意下这个问题。脚本虽然短小,但非常实用、精悍,可避免到Windows 下去下载局域网检测工具。平时我们在日常工作中也应该注意多收集、多写一些这样的脚本,以达到简化运维工作的目的。

    相关资源:敏捷开发V1.0.pptx
    最新回复(0)