python实现的ssh失败5次拉黑ip

使用python实现的从/var/log/secure中读取约两小时内登录失败超过5次的ip加入黑名单。
如果有误删,可以加入白名单,并删除/etc/hosts.deny。
仅自己玩一玩用,实际上有更完善的fail2ban软件可以使用

from collections import Counter
import re
import datetime
import os


secure_log_dir = '/var/log/secure'
deny_dir = '/etc/hosts.deny'

with open(secure_log_dir, 'r') as f:
    lines = f.readlines()

last_time = lines[-1].split(' ')[2]
last_hour = last_time.split(':')[0]

hour_in_day = list(range(24))
hour_in_day = hour_in_day + hour_in_day
margin = 2
def judge(last_hour, source):
    available = hour_in_day[last_hour+24-margin:last_hour+24+1]
    return source in available

logs = []
for i in lines[::-1]:
    hour = i.split(' ')[2].split(':')[0]
    if not judge(int(last_hour), int(hour)):
        break
    logs.append(i)

logs = [x.strip() for x in logs if 'Failed' in x] 

with open('/root/secure_log_save', 'w') as f:
    for l in logs:
        f.write(l + '\n')

# lines = [x for x in lines if x.split(' ')[1] == date]

ip_counter = Counter()
for x in logs:
    result = re.findall(r"(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)", x)
    ip_counter.update(result)

# 在/etc/hosts.deny中找已经被封的ip防止重复被封
with open(deny_dir, 'r') as f:
    denyed_hosts = f.readlines()
denyed_hosts = [x for x in denyed_hosts if x[0] != '#']
denyed_hosts = [x.split(':')[1] for x in denyed_hosts]
print('denyed_hosts', denyed_hosts)

# 读取白名单,主要用于解封ip。每天0点d删白名单
if os.path.exists('/root/whitelist'):
    with open('/root/whitelist', 'r') as f:
        denyed_hosts += [x.strip() for x in f.readlines()]
print('denyed_hosts', denyed_hosts)

deny_f = open(deny_dir, 'a')
log_f = open('/root/deny_log', 'a')
for k,v in ip_counter.items():
    if v >= 5:
        if k not in denyed_hosts:
            deny_f.write(f'sshd:{k}:deny' + '\n')
        log_f.write(str(datetime.datetime.now()) + ' ' + k + '\n')
f.close()

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值