centos禁用主机黑名单访问python脚本hosts.deny secure

整体思路:
①读取secure文件日志
②筛选登录失败日志
③抓起登录失败IP,判断失败次数,超过6次加入黑名单
④判断抓起的IP是否已存在黑名单中
⑤追加模式写入黑名单文件

import re
from time import sleep


while True:
    ip_list = []
    deny_ip = []
    # 读取安全日志
    with open('/var/log/secure', 'r', encoding='utf-8') as f:
        for l in f.readlines():
            # 筛选登录失败日志
            if 'Failed' in l:
                # print(l)
                # 正则失败IP
                ip_l = re.findall(r'\d+\.\d+\.\d+\.\d+', l)
                # 失败IP加入列表
                ip_list.append(ip_l[0])
        # 列表去重
        ip_list2 = list(set(ip_list))
        # print(len(ip_list))
        for ip in ip_list2:
            # print(ip)
            # 计算机ip再列表中出现的次数
            # print(ip_list.count(ip))
            # 过滤失败次数大于等于6次IP
            if ip_list.count(ip) >= 6:
                deny_ip.append(ip)
        # print(deny_ip)
    
    deny_ip2 = []
    with open('/etc/hosts.deny', 'r', encoding='utf-8') as f2:
        str1 = f2.read()
        for ip2 in deny_ip:
            # 判断是否在禁用名单内
            if 'sshd:' + ip2 + ':deny' not in str1:
                # print(ip2)
                deny_ip2.append(ip2)
    # 将IP追加模式写入禁用名单内
    with open('/etc/hosts.deny', 'a+', encoding='utf-8') as f3:
        for ip3 in deny_ip2:
            str2 = 'sshd:' + ip3 + ':deny' + '\n'
            print(str2)
            f3.write(str2)
    # 每小时执行一次
    sleep(3600)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值