整体思路:
①读取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)