解决方法:根据邮件日志提取出恶意攻击的ip进行过滤
#!/usr/bin/env python #-*- coding:utf-8 -*- #crotabRun /usr/bin/python ipfilter.py >/dev/null 2>&1 import sys import re import os import logging import time now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) day = time.strftime('%Y-%m-%d',time.localtime(time.time())) os.system("grep 'authentication failure' /var/log/maillog > 1.txt") f = open("iplist.txt") # 返回一个文件对象 line = f.readline() # 调用文件的 readline()方法 ipOldList = [] while line: if line: ipOldList.append(line.strip('\n')) # print(line, end = '') # 在 Python 3中使用 line = f.readline() f.close() f = open("1.txt") line = f.readline() ip_list = [] while line: ip = re.findall(r'\d+.\d+.\d+.\d+', line) if (len(ip) == 2): if ip[1] not in ipOldList: ip_list.append(ip[1]) line = f.readline() f.close() logging.basicConfig(filename = os.path.join(os.getcwd(), 'log.txt'), level = logging.DEBUG) if ip_list: #ip白名单 whiteList = ['27.54.226.101','27.54.226.99','27.54.226.104','27.54.226.100','27.54.226.102','27.54.226.103','58.211.116.10'] #去除数组中重复的值 def unique(L): return [x for x in L if x not in locals()['_[1]']] update = 0 if ip_list: ipdrop = open('ipdrop.sh','a') iplist = open('iplist.txt','a') try: for ip in unique(ip_list): if ip not in whiteList: update = 1 rule = "\n/sbin/iptables -I INPUT -s %s -j DROP" %(ip) ipdrop.write(rule) iplist.write("\n"+ip) if update == 0: logging.debug(now + ' 文件不需要更新~~') finally: ipdrop.close() iplist.close() else: logging.debug(now + ' 无ip需要过滤~~') if update == 1: os.system('/sbin/service iptables restart') os.system("/bin/bash "+os.path.join(os.getcwd(), 'ipdrop.sh')) logging.debug(now + ' 更新iptables成功~~') os.system("cp /var/log/maillog /var/log/maillog_"+day) os.system("echo '' > /var/log/maillog") else: logging.debug(now + ' 没有恶意攻击的IP~~')