百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

Oracle监听日志分析

moboyou 2025-04-09 13:40 45 浏览

1.把监听日志和脚本放到一个目录

yuyuz-mac:analyze-listenerlog yuyuz$ pwd
/Users/yuyuz/python/analyze-listenerlog
yuyuz-mac:analyze-listenerlog yuyuz$ ls
listener.log	lsnrlog.py

2.执行脚本

yuyuz-mac:analyze-listenerlog yuyuz$ python lsnrlog.py 
提取到的成功时间戳数量: 1920
提取到的失败时间戳数量: 15081
提取到的总时间戳数量: 17001
HTML 文件生成成功
yuyuz-mac:analyze-listenerlog yuyuz$ ls
connection_analysis.html	listener.log			lsnrlog.py

3.查看结果

支持区域放大/查看数据/线图柱图切换

4.代码

import re
from datetime import datetime
from pyecharts import options as opts
from pyecharts.charts import Line, Page


def parse_log(log_text):
    """
    解析日志文本,提取包含CONNECT_DATA字段行的时间戳、SERVICE、HOST和IP,并区分成功和失败连接
    :param log_text: 日志文本
    :return: 成功时间戳列表、失败时间戳列表、总时间戳列表、SERVICE信息列表、HOST信息列表、IP信息列表
    """
    success_timestamps = []
    failure_timestamps = []
    total_timestamps = []
    services = []
    hosts = []
    ips = []
    pattern = r'(\d{2}-[A-Z]{3}-\d{4} \d{2}:\d{2}:\d{2})|(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})'
    service_pattern = r'SERVICE_NAME=(\w+)'
    host_pattern = r'HOST=(\w+)'
    ip_pattern = r'HOST=(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'

    for line in log_text.split('\n'):
        if 'CONNECT_DATA' in line:
            match = re.search(pattern, line)
            if match:
                timestamp_str = match.group(0)
                try:
                    if '-' in timestamp_str[0:3]:
                        timestamp = datetime.strptime(timestamp_str, '%d-%b-%Y %H:%M:%S')
                    else:
                        timestamp = datetime.strptime(timestamp_str, '%Y-%m-%dT%H:%M:%S')
                    total_timestamps.append(timestamp)
                    if line.strip().endswith('0'):
                        success_timestamps.append(timestamp)
                    else:
                        failure_timestamps.append(timestamp)

                    service_match = re.search(service_pattern, line)
                    host_match = re.search(host_pattern, line)
                    ip_match = re.search(ip_pattern, line)

                    service = service_match.group(1) if service_match else None
                    host = host_match.group(1) if host_match else None
                    ip = ip_match.group(1) if ip_match else None

                    services.append((timestamp, service))
                    hosts.append((timestamp, host))
                    ips.append((timestamp, ip))
                except ValueError:
                    print(f"无法解析时间戳: {timestamp_str}")
    print(f"提取到的成功时间戳数量: {len(success_timestamps)}")
    print(f"提取到的失败时间戳数量: {len(failure_timestamps)}")
    print(f"提取到的总时间戳数量: {len(total_timestamps)}")
    return success_timestamps, failure_timestamps, total_timestamps, services, hosts, ips


def count_connections(timestamps, interval):
    """
    统计不同时间间隔的连接数
    :param timestamps: 时间戳列表
    :param interval: 时间间隔,如 'H' 表示小时,'T' 表示分钟,'S' 表示秒
    :return: 时间间隔和对应的连接数
    """
    counts = {}
    for timestamp in timestamps:
        if interval == 'H':
            key = timestamp.replace(minute=0, second=0, microsecond=0).strftime('%Y-%m-%d %H:00:00')
        elif interval == 'T':
            key = timestamp.replace(second=0, microsecond=0).strftime('%Y-%m-%d %H:%M:00')
        elif interval == 'S':
            key = timestamp.replace(microsecond=0).strftime('%Y-%m-%d %H:%M:%S')
        if key in counts:
            counts[key] += 1
        else:
            counts[key] = 1
    return sorted(counts.items())


def count_by_attribute(data, interval, attribute):
    """
    按指定属性统计不同时间间隔的连接数
    :param data: 包含时间戳和属性的元组列表
    :param interval: 时间间隔,如 'H' 表示小时,'T' 表示分钟,'S' 表示秒
    :param attribute: 属性名称
    :return: 以属性为键,时间间隔和对应连接数为值的字典
    """
    counts = {}
    for timestamp, attr in data:
        if attr is None:
            continue
        if interval == 'H':
            key = timestamp.replace(minute=0, second=0, microsecond=0).strftime('%Y-%m-%d %H:00:00')
        elif interval == 'T':
            key = timestamp.replace(second=0, microsecond=0).strftime('%Y-%m-%d %H:%M:00')
        elif interval == 'S':
            key = timestamp.replace(microsecond=0).strftime('%Y-%m-%d %H:%M:%S')
        if attr not in counts:
            counts[attr] = {}
        if key in counts[attr]:
            counts[attr][key] += 1
        else:
            counts[attr][key] = 1
    for attr in counts:
        counts[attr] = sorted(counts[attr].items())
    return counts


def create_line_chart(success_data, failure_data, total_data, interval):
    """
    创建线图
    :param success_data: 成功连接的时间间隔和对应的连接数
    :param failure_data: 失败连接的时间间隔和对应的连接数
    :param total_data: 总连接的时间间隔和对应的连接数
    :param interval: 时间间隔,如 '小时','分钟','秒'
    :return: 线图对象
    """
    x_data = sorted(set([item[0] for item in success_data + failure_data + total_data]))
    success_y_data = [next((item[1] for item in success_data if item[0] == x), 0) for x in x_data]
    failure_y_data = [next((item[1] for item in failure_data if item[0] == x), 0) for x in x_data]
    total_y_data = [next((item[1] for item in total_data if item[0] == x), 0) for x in x_data]

    line = (
        Line(init_opts=opts.InitOpts(bg_color="#f5f5f5", width="100%"))
        .add_xaxis(x_data)
        .add_yaxis(
            series_name=f"成功连接总数/{interval}",
            y_axis=success_y_data,
            label_opts=opts.LabelOpts(is_show=False),
            linestyle_opts=opts.LineStyleOpts(width=2, color="#228B22"),
            symbol="circle",
            symbol_size=6,
            itemstyle_opts=opts.ItemStyleOpts(color="#228B22")
        )
        .add_yaxis(
            series_name=f"失败连接总数/{interval}",
            y_axis=failure_y_data,
            label_opts=opts.LabelOpts(is_show=False),
            linestyle_opts=opts.LineStyleOpts(width=2, color="#FF0000"),
            symbol="circle",
            symbol_size=6,
            itemstyle_opts=opts.ItemStyleOpts(color="#FF0000")
        )
        .add_yaxis(
            series_name=f"总连接数/{interval}",
            y_axis=total_y_data,
            label_opts=opts.LabelOpts(is_show=False),
            linestyle_opts=opts.LineStyleOpts(width=2, color="#FF6347"),
            symbol="circle",
            symbol_size=6,
            itemstyle_opts=opts.ItemStyleOpts(color="#FF6347")
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(
                title=f"连接情况统计/{interval}",
                title_textstyle_opts=opts.TextStyleOpts(font_size=20, color="#333")
            ),
            toolbox_opts=opts.ToolboxOpts(is_show=True),
            xaxis_opts=opts.AxisOpts(
                name=interval,
                axislabel_opts=opts.LabelOpts(rotate=45, font_size=12, color="#666"),
                name_textstyle_opts=opts.TextStyleOpts(font_size=14, color="#333")
            ),
            yaxis_opts=opts.AxisOpts(
                name="连接数",
                axislabel_opts=opts.LabelOpts(font_size=12, color="#666"),
                name_textstyle_opts=opts.TextStyleOpts(font_size=14, color="#333")
            ),
            tooltip_opts=opts.TooltipOpts(trigger="axis"),
            legend_opts=opts.LegendOpts(
                type_="scroll",
                orient="vertical",
                pos_left="right",
                pos_top="middle",
                textstyle_opts=opts.TextStyleOpts(font_size=8, color="#333")
            )
        )
    )
    return line


def create_attribute_line_chart(counts, interval, attribute):
    """
    创建按属性统计的线图
    :param counts: 以属性为键,时间间隔和对应连接数为值的字典
    :param interval: 时间间隔,如 '小时','分钟','秒'
    :param attribute: 属性名称
    :return: 线图对象
    """
    all_x_data = set()
    for data in counts.values():
        for x, _ in data:
            all_x_data.add(x)
    x_data = sorted(all_x_data)

    line = Line(init_opts=opts.InitOpts(bg_color="#f5f5f5", width="100%"))
    line.add_xaxis(x_data)

    for attr, data in counts.items():
        y_data = [next((item[1] for item in data if item[0] == x), 0) for x in x_data]
        line.add_yaxis(
            series_name=f"{attr}/{interval}",
            y_axis=y_data,
            label_opts=opts.LabelOpts(is_show=False),
            linestyle_opts=opts.LineStyleOpts(width=2),
            symbol="circle",
            symbol_size=6
        )

    line.set_global_opts(
        title_opts=opts.TitleOpts(
            title=f"{attribute} 连接情况统计/{interval}",
            title_textstyle_opts=opts.TextStyleOpts(font_size=20, color="#333")
        ),
        toolbox_opts=opts.ToolboxOpts(is_show=True),
        xaxis_opts=opts.AxisOpts(
            name=interval,
            axislabel_opts=opts.LabelOpts(rotate=45, font_size=12, color="#666"),
            name_textstyle_opts=opts.TextStyleOpts(font_size=14, color="#333")
        ),
        yaxis_opts=opts.AxisOpts(
            name="连接数",
            axislabel_opts=opts.LabelOpts(font_size=12, color="#666"),
            name_textstyle_opts=opts.TextStyleOpts(font_size=14, color="#333")
        ),
        tooltip_opts=opts.TooltipOpts(trigger="axis"),
        legend_opts=opts.LegendOpts(
            type_="scroll",
            orient="vertical",
            pos_left="right",
            pos_top="middle",
            textstyle_opts=opts.TextStyleOpts(font_size=8, color="#333")
        )
    )
    return line


def main():
    """
    主函数,从文件读取日志并生成包含多个线图的网页
    """
    try:
        with open('listener.log', 'r', encoding='utf-8') as file:
            log_text = file.read()
        success_timestamps, failure_timestamps, total_timestamps, services, hosts, ips = parse_log(log_text)

        # 统计每小时、每分钟、每秒的成功、失败和总连接数
        intervals = ['H', 'T', 'S']
        interval_names = ['小时', '分钟', '秒']
        page = Page()

        for interval, interval_name in zip(intervals, interval_names):
            hourly_success_data = count_connections(success_timestamps, interval)
            hourly_failure_data = count_connections(failure_timestamps, interval)
            hourly_total_data = count_connections(total_timestamps, interval)
            hourly_chart = create_line_chart(hourly_success_data, hourly_failure_data, hourly_total_data, interval_name)
            page.add(hourly_chart)

        # 按SERVICE、HOST、IP统计并绘制线图
        attributes = [('SERVICE', services), ('HOST', hosts), ('IP', ips)]
        for attribute_name, attribute_data in attributes:
            for interval, interval_name in zip(intervals, interval_names):
                counts = count_by_attribute(attribute_data, interval, attribute_name)
                chart = create_attribute_line_chart(counts, interval_name, attribute_name)
                page.add(chart)

        page.render("connection_analysis.html")

        # 添加版权信息到 HTML 文件
        copyright_info = '
声明:仅用作兴趣爱好和测试使用,请勿商用,不承担任何商业责任。--张宇--
' with open('connection_analysis.html', 'a', encoding='utf-8') as f: f.write(copyright_info) print("HTML 文件生成成功") except FileNotFoundError: print("未找到 listener.log 文件,请确保文件存在。") except Exception as e: print(f"发生错误: {e}") if __name__ == "__main__": main()

相关推荐

php宝塔搭建部署实战服务类家政钟点工保姆网站源码

大家好啊,我是测评君,欢迎来到web测评。本期给大家带来一套php开发的服务类家政钟点工保姆网站源码,感兴趣的朋友可以自行下载学习。技术架构PHP7.2+nginx+mysql5.7+JS...

360自动收录简介及添加360自动收录功能的详细教程

以前我们都是为博客站点添加百度实时推送功能,现在360已经推出了自动收录功能,个人认为这个功能应该跟百度的实时推送功能差不多,所以我们也应该添加上这个功能,毕竟360在国内的份额还是不少的。360自动...

介绍一个渗透测试中使用的WEB扫描工具:Skipfish

Skipfish简介Skipfish是一款主动的、轻量级的Web应用程序安全侦察工具。它通过执行递归爬取和基于字典的探测来为目标站点准备交互式站点地图。该工具生成的最终报告旨在作为专业Web应用程序安...

好程序员大数据培训分享Apache-Hadoop简介

好程序员大数据培训分享Apache-Hadoop简介  好程序员大数据培训分享Apache-Hadoop简介,一、Hadoop出现的原因:现在的我们,生活在数据大爆炸的年代。国际数据公司已经预测在20...

LPL比赛数据可视化,完成这个项目,用尽了我的所有Python知识

LPL比赛数据可视化效果图完成这个项目,我感觉我已经被掏空了,我几乎用尽了我会的所有知识html+css+javascript+jQuery+python+requests+numpy+mysql+p...

网站被谷歌标记“有垃圾内容”但找不到具体页面?

谷歌的垃圾内容判定机制复杂,有时违规页面藏得深(如用户注册页、旧测试内容),或是因第三方插件漏洞被注入垃圾代码,导致站长反复排查仍毫无头绪。本文提供一套低成本、高执行性的解决方案。你将学会如何利用谷歌...

黑客必学知识点--如何轻松绕过CDN,找到真实的IP地址

信息收集(二)1、cms识别基础为什么要找CMS信息呢?因为有了CMS信息之后,会给我们很多便利,我们可以搜索相应CMS,有没有公开的漏洞利用根据敏感文件的判断:robots.txt文件robots....

Scrapy 爬虫完整案例-提升篇

1Scrapy爬虫完整案例-提升篇1.1Scrapy爬虫进阶案例一Scrapy爬虫案例:东莞阳光热线问政平台。网站地址:http://wz.sun0769.com/index.php/que...

如何写一个疯狂的爬虫!

自己在做张大妈比价(http://hizdm.com)的时候我先后写了两个版本的爬虫(php版本和python版本),虽然我试图将他们伪装的很像人但是由于京东的价格接口是一个对外开放的接口,如果访问频...

程序员简历例句—范例Java、Python、C++模板

个人简介通用简介:有良好的代码风格,通过添加注释提高代码可读性,注重代码质量,研读过XXX,XXX等多个开源项目源码从而学习增强代码的健壮性与扩展性。具备良好的代码编程习惯及文档编写能力,参与多个高...

Python爬虫高级之JS渗透登录新浪微博 | 知了独家研究

小伙伴们看到标题可能会想,我能直接自己登陆把登陆后的cookie复制下来加到自定义的请求头里面不香嘛,为什么非要用python模拟登录的过程?如果我们是长期爬取数据,比如每天早上中午和晚上定时爬取新浪...

使用Selenium实现微博爬虫:预登录、展开全文、翻页

前言想实现爬微博的自由吗?这里可以实现了!本文可以解决微博预登录、识别“展开全文”并爬取完整数据、翻页设置等问题。一、区分动态爬虫和静态爬虫1、静态网页静态网页是纯粹的HTML,没有后台数据库,不含程...

《孤注一掷》关于黑客的彩蛋,你知道多少?

电影总是能引发人们的好奇心,尤其是近日上映的电影《孤注一掷》。这部电影由宁浩监制,申奥编剧执导,是一部反诈骗犯罪片。今天给大家讲解一下影片潘生用的什么语言,以及写了哪些程序。揭秘影片中的SQL注入手法...

python爬虫实战之Headers信息校验-Cookie

一、什么是cookie上期我们了解了User-Agent,这期我们来看下如何利用Cookie进行用户模拟登录从而进行网站数据的爬取。首先让我们来了解下什么是Cookie:Cookie指某些网站为了辨别...

「2022 年」崔庆才 Python3 爬虫教程 - urllib 爬虫初体验

首先我们介绍一个Python库,叫做urllib,利用它我们可以实现HTTP请求的发送,而不用去关心HTTP协议本身甚至更低层的实现。我们只需要指定请求的URL、请求头、请求体等信息即...