使用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()