随心一记

一二三四五,上山打老鼠


  • 首页

  • 归档

  • 标签
ywcsb

ywcsb

游戏可以不玩,小说不能不看。

153 日志
3 分类
42 标签
RSS
GitHub 知乎 随心一记
Links
  • 随心一记
  • 追梦人物的
  • MSDN

Python3 过滤十分钟之内的Nginx日志文件(json格式)并添加到iptables

发表于 2019-01-26 | 阅读 1029 | 分类于 Python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name:     iptables
   Author :       lihuabing
   date:          2018/8/12
-------------------------------------------------
   Change Activity:
                   2018/8/12:
-------------------------------------------------
"""
__author__ = 'lihuabing'

def host(host, now_time, before_time):
    import os
    if host['host'] != str("www.ywcsb.vip") and host["host"] != str("ywcsb.vip"):
        ip = host["remote_addr"]
        iptables = os.system("iptables -L -v -n --line-numbers | grep %s" % ip)
        if iptables:
            os.system("iptables -I INPUT 1 -s %s -j DROP" % ip)
            with open("/data/script/iptables-DROP.txt", 'a+') as f:
                f.write("【%s】-【%s】之间的IP地址:%s\n" % (before_time, now_time, ip))


def timestamp(column):
    import time
    # 当前时间
    now_time = time.strftime("%H:%M", time.localtime())
    now_time_ip = time.strftime("%Y-%m-%d %H:%M:%S")
    now_time_stamp = time.mktime(time.strptime(now_time, '%H:%M'))
    # 10分钟之前的时间
    t = time.localtime(time.time() - 600)
    before_time_ip = time.strftime("%Y-%m-%d %H:%M:%S", t)
    before_time = time.strftime("%H:%M", t)
    before_time_stamp = time.mktime(time.strptime(before_time, '%H:%M'))
    # 获取log日志里的时间
    str = column["timestamp"]
    # .split 是截取分割字符串(和awk形式一样)
    str_time = ('%s:%s' % (str.split(':')[1], str.split(':')[2]))
    str_time_stamp = time.mktime(time.strptime(str_time.split()[0], '%H:%M'))
    # print('%s-%s-%s' % (now_time, before_time, str_time.split()[0]))
    if str_time_stamp <= now_time_stamp and str_time_stamp >= before_time_stamp:
        host(column, now_time_ip, before_time_ip)


def wenjian():
    with open('access.json', 'r') as f:
        import json
        for line in f.readlines():
            try:
                res = json.loads(line.strip())
            except BaseException:
                pass
            else:
                timestamp(res)
                # print(Chom, res['timestamp'])


if __name__ == '__main__':
    import time
    print(time.strftime("%H:%M:%S", time.localtime()))
    wenjian()
    print(time.strftime("%H:%M:%S", time.localtime()))
觉得不错,支持一下!
geerniya WeChat Pay

微信打赏

geerniya Alipay

支付宝打赏

# Nginx # Python # iptables # 防火墙
Mac下安装SecureCRT并激活
shell 过滤十分钟之内的Nginx日志文件(json格式)并添加到iptables(V2))

发表评论

共 0 条评论

    暂无评论
© 2018 - 2022 ywcsb
冀ICP备17022045号-1
Supported by 腾讯云