我孤身走在路上, 石子在雾中发亮,夜很安静,荒原面对太空,星星互诉衷肠
Python筛选日志脚本
Python筛选日志脚本

Python筛选日志脚本

前段时间心血来潮,想统计一下所有分部的作业人数,大概思路是通过squid的日志,来查找想要内容,通过判断,统计终端作业人数

大概思路是,以IP统计,只要是登录了,并且访问了业务系统的就算一个作业人数,且不重复计算,本来想要用python来做逻辑,感觉没有linux的grep这么简单,所以就有了下面的代码:

import paramiko
import sys

ssh = paramiko.SSHClient()
# 允许将信任的主机自动加入到host_allow 列表,此方法必须放在connect方法的前面
branches = {
    """
    ip : 分公司的代理地址
    log_prefix : 内网地址前缀,尽量设置到C段
    log_condition :过滤条件,根据分公司访问的页面不同,精准筛选
    """
    # 餐饮门店
    'X街X门店': {'ip': '分部代理服务器地址', 'log_prefix': '分部地址的前缀,例如:192.168.5', 'log_condition': '判断条件'},
    # 工厂车间
    'X车间X流水线': {'ip': '分部代理服务器地址', 'log_prefix': '分部地址的前缀,例如:192.168.5', 'log_condition': '判断条件'},
    # 行政后勤
    'X分部后勤': {'ip': '分部代理服务器地址', 'log_prefix': '分部地址的前缀,例如:192.168.5', 'log_condition': '判断条件'}
}
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

for branch, info in branches.items():
    # 调用connect方法连接服务器
    ssh.connect(hostname=info['ip'], port=22, username='代理服务器的用户名', password='代理服务器的密码')
    # 执行命令
    stdin, stdout, stderr = ssh.exec_command(
        f"grep '{info['log_prefix']}' /var/log/squid/access.log | grep  '{info['log_condition']}' | awk '{{print $2}}' | sort | uniq")
    # 结果放到stdout中,如果有错误将放到stderr中
    i = 0
    for line in stdout:
        i += 1
    print(f'{branch}作业人数为:{i}人')
    for line in stderr:
        print(line)
    ssh.close()
sys.exit()

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

43 − 37 =