当前位置: 首页 > news >正文

Python 脚本学习(三),日志分析脚本,文件差异对比,HTTP状态检测

日志分析脚本:

#!/usr/local/python27/bin/python2.7
# coding=utf-8

import pygal
import re
import os
import sys
import datetime

BASE_PATH = "./"


def extract(path):
    ip = dict()
    time = dict()
    status = dict()
    version = dict()
    method = dict()
    with open(path) as f:
        for line in f:
            matched = reobj.search(line)
            if not matched:
                continue
            log_obj = matched.groupdict()
            if log_obj.get("ip") not in ip.keys():
                ip[log_obj.get("ip")] = 0
            ip[log_obj.get("ip")] += 1
            origin_time = log_obj.get("time")
            if not origin_time:
                continue
            dt = datetime.datetime.strptime(origin_time,'%d/%b/%Y:%H:%M:%S')
            dt_s = dt.strftime('%Y-%m-%d %H')
            if dt_s not in time.keys():
                time[dt_s] = 0
            time[dt_s] += 1
            if log_obj.get('status') not in status.keys():
                status[log_obj.get('status')] = 0
            status[log_obj.get('status')] += 1
            if log_obj.get('version') not in version.keys():
                version[log_obj.get('version')] = 0
            version[log_obj.get('version')] += 1
            if log_obj.get("method") not in method.keys():
                method[log_obj.get("method")] = 0
            method[log_obj.get("method")] += 1
    return ip,time,status,version,method

def make_path(dt):
    path = os.path.join(BASE_PATH,dt)
    if not os.path.exists(path):
        os.makedirs(path)
    return path

def time_graph(time,dt):
    chart = pygal.Bar()
    chart.title = "Access of %s" % dt
    keys = ['%s %2d' % (dt,x) for x in range(24)]
    values = [time.get(key) for key in keys]

    chart.x_labels = [x.split()[1] for x in keys]
    chart.add("Access",values)
    path = make_path(dt)
    chart.render_to_file(os.path.join(path,"time.svg"))


def status_graph(status,dt):
    chart = pygal.Pie()
    chart.title = "Status of %s" % dt
    for k,v in status.items():
        chart.add(k,v)
    path = make_path(dt)
    chart.render_to_file(os.path.join(path,"status.svg"))



def version_graph(vsersion,dt):
    chart = pygal.Pie()
    chart.title = "versions of %s" % dt
    for k,v in version.items():
        chart.add(k,v)
    path = make_path(dt)
    chart.render_to_file(os.path.join(path,"version.svg"))


def method_graph(method,dt):
    chart = pygal.Pie()
    chart.title = "methods of %s" % dt
    for k,v in method.items():
        chart.add(k,v)
    path = make_path(dt)
    chart.render_to_file(os.path.join(path,"method.svg"))

if __name__ == '__main__':
    log_file = sys.argv[1]
    dt = sys.argv[2]
    ip,time,status,version,method = extract(log_file)
    time_graph(time,dt)
    status_graph(status,dt)
    version_graph(version,dt)
    method_graph(method,dt)


文件差异对比:

#!/usr/local/python27/bin/python2.7
import difflib
import sys

try:
    textfile1=sys.argv[1]
    textfile2=sys.argv[2]
except e:
    print("Error:" + str(e))
    sys.exit()

def readfile(filename):
    try:
        fileHandle = open(filename,'rb')
        text=fileHandle.read().splitlines()
        fileHandle.close()
        return text

    except IOError as a:
        print("Error:" + str(a))
        sys.exit()

if textfile1 =="" or textfile2=="":
    print('Usage:filediif.py filename1 filename2')
    sys.exit()

text1_lines = readfile(textfile1)
text2_lines = readfile(textfile2)

d = difflib.HtmlDiff()
a = d.make_file(text1_lines,text2_lines)
print(a)

输出结果:

./filediff.py aa1.txt aa2.txt >diff.html

wKioL1X4yHCRLwFyAACXbe1qGgE183.jpg

HTTP访问脚本

#!/usr/local/python27/bin/python2.7
import urllib2

req = urllib2.urlopen('http://weather.yahooapis.com/forecastrss?w=2151849&u=c')

print(req.read())


HTTP状态检测—适用于单域名多主机DNS负载均衡场景

#!/usr/local/python27/bin/python2.7
import dns.resolver
import os
import httplib

iplist = []

appdomain='www.hello.com'

def get_iplist(domain=""):
    try:
        A = dns.resolver.query(domain,'A')
    except e:
        print("dns resolver error:" + str(e))
        return

    for i in A.response.answer:
        for j in i.items:
            iplist.append(j.address)
    return True

def checkip(ip):
    checkurl=ip+":80"
    getcontent=""
    httplib.socket.setdefaulttimeout(5)
    conn=httplib.HTTPConnection(checkurl)

    try:
        conn.request("GET","/",headers = {"Host": appdomain})

        r = conn.getresponse()
        getcontent = r.read(15)
    finally:
        if getcontent == "<!DOCTYPE html>":
            print (ip+" [OK]")
        else:
            print (ip+" [Error]")

if __name__ == "__main__":
    if get_iplist(appdomain) and len(iplist)>0:
        for ip in iplist:
            checkip(ip)
    else:
        print("dns resolver error")


DNS解析脚本

#!/usr/local/python3/bin/python3
import dns.resolver

domain = input('please input an domain: ')
A = dns.resolver.query(domain,'A')
for i in A.response.answer:
    for j in i.items:
        print(j.address)


MX记录解析

#!/usr/local/python3/bin/python3
import dns.resolver
domain = input('please input an domain: ')
#这里接收两个参数的传入,需要解析的域名,解析的记录类型;
MX = dns.resolver.query(domain,'MX')
for i in MX:
    print('MX preference =', i.preference, 'mail exchanger = ', i.exchange)


相关文章:

  • 几种.NET平台数据持久化框架介绍
  • php中Maximum execution time of 120 seconds exceeded时间超时错误解决方案
  • 矩阵键盘 数码管
  • 使用U盘代替光盘来刻录ISO镜像文件的方法
  • linux 函数
  • MyBatis笔记——Mapper动态代理
  • python教程
  • C语言 实现 给定两个整形变量的值,将两个值的内容进行交换
  • 更为适合并发的极简易队列
  • 2016年一些面试题的整理和心情--1异或到100
  • WINDOW10下修正CHROME字体问题解决方案
  • 不能在 DropDownList 中选择多个项。其解决办法及补充
  • 如果使用得当,MySQL 也可以化身 NoSQL
  • 一些非常经典的awk小技巧
  • Tarjan 求强连通分量
  • hexo+github搭建个人博客
  • 【编码】-360实习笔试编程题(二)-2016.03.29
  • Android 初级面试者拾遗(前台界面篇)之 Activity 和 Fragment
  • Git初体验
  • iOS 系统授权开发
  • k个最大的数及变种小结
  • Linux学习笔记6-使用fdisk进行磁盘管理
  • mac修复ab及siege安装
  • mysql 5.6 原生Online DDL解析
  • React+TypeScript入门
  • Sass 快速入门教程
  • tweak 支持第三方库
  • 对话 CTO〡听神策数据 CTO 曹犟描绘数据分析行业的无限可能
  • 记一次和乔布斯合作最难忘的经历
  • 利用阿里云 OSS 搭建私有 Docker 仓库
  • 前端临床手札——文件上传
  • 如何抓住下一波零售风口?看RPA玩转零售自动化
  • 小而合理的前端理论:rscss和rsjs
  • 转载:[译] 内容加速黑科技趣谈
  • 06-01 点餐小程序前台界面搭建
  • FaaS 的简单实践
  • Spark2.4.0源码分析之WorldCount 默认shuffling并行度为200(九) ...
  • 回归生活:清理微信公众号
  • 京东物流联手山西图灵打造智能供应链,让阅读更有趣 ...
  • ![CDATA[ ]] 是什么东东
  • # Swust 12th acm 邀请赛# [ K ] 三角形判定 [题解]
  • ###STL(标准模板库)
  • (03)光刻——半导体电路的绘制
  • (4)通过调用hadoop的java api实现本地文件上传到hadoop文件系统上
  • (vue)el-checkbox 实现展示区分 label 和 value(展示值与选中获取值需不同)
  • (笔试题)分解质因式
  • (多级缓存)多级缓存
  • (转)linux下的时间函数使用
  • .Net Attribute详解(上)-Attribute本质以及一个简单示例
  • .net core IResultFilter 的 OnResultExecuted和OnResultExecuting的区别
  • .NET MAUI学习笔记——2.构建第一个程序_初级篇
  • .NET 分布式技术比较
  • .net 受管制代码
  • @GlobalLock注解作用与原理解析
  • [ JavaScript ] JSON方法