Python教程

Python小程序(三):自动读取secure文件,并封禁异常IP地址

本文主要是介绍Python小程序(三):自动读取secure文件,并封禁异常IP地址,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Python小程序(三):自动读取secure文件,并封禁异常IP地址

Python小白编写的内容。欢迎大家指正。

#! python
# -*- coding:utf-8 -*-
# 时间:20220812
# 作者:ColoFly
# 转载请注明出处及作者
import os,re,time,datetime,openpyxl
from collections import Counter

sec_log = open(r'secure', 'r', encoding='utf-8')
sec_line = sec_log.readlines()

End_time = datetime.datetime(2033, 12, 31, 23, 59, 59) #循环结束时间

#正则表达式,用于匹配IP地址
IpRegex = re.compile(r'''(
    (\d{1,3})  #IP address A class
    \.
    (\d{1,3})  #IP address B class
    \.
    (\d{1,3})  #IP address C class
    \.
    (\d{1,3})  #IP address D class
)''', re.VERBOSE)

Col_A = 'A' #定义表格prohibit_ip列号
Col_B = 'B' #定义表格prohibit_time列号

if __name__ == '__main__':
    if os.path.exists('prohibit_ip.xlsx'):
        print('prohibit_ip.xlsx is exists')
    else:
        table = ["prohibit_ip", "prohibit_time"]
        wb = openpyxl.Workbook()
        sheet = wb.active
        sheet.title = "Ip_sheet"
        row = 1
        for i in range(len(table)):
            sheet.cell(row, i+1, table[i])
        wb.save(filename = "prohibit_ip.xlsx")
        print('prohibit_ip.xlsx created successfully')


file_location = 'prohibit_ip.xlsx' #定义存放文件名称
workbook = openpyxl.load_workbook('prohibit_ip.xlsx') #加载表格簿
Ip_sheet = workbook.active #读取表格

while datetime.datetime.now() < End_time:
    #读取每一行中是否存在'Failed password',如果存在则循环这一行中内容查找IP地址。因为相关文件
    #来自Linux /var/log/secure文件中,就不再使用IP模块进行IP地址校验。
    file_location = 'prohibit_ip.xlsx'  # 定义存放文件名称
    workbook = openpyxl.load_workbook('prohibit_ip.xlsx')  # 加载表格簿
    Ip_sheet = workbook.active  # 读取表格
    Ip_list = {}

    matches = []
    for line in sec_line:
        if 'Failed password' in line:
            for Ip in IpRegex.findall(line):
                matches.append(Ip[0])
                #print(matches)

    Ip_count = Counter(matches)
    print(Ip_count)

    for k,v in Ip_count.items():
        #读取单元格

        if k in Ip_list:
            print('Ok')
            continue
        else:
            #print('False')
            if int(v) > 3:
                print('iptables -A INPUT -p tcp -s ' + k + ' --dport 22 -j DROP')
                Ip_sheet[Col_A + str(Max_Row)] = k
                Ip_sheet[Col_B + str(Max_Row)] = datetime.datetime.now()
                workbook.save('prohibit_ip.xlsx')

        Max_Row = Ip_sheet.max_row + 1
        Max_Col = Ip_sheet.max_column + 1

        for Row in range(2, Max_Row):
            Ip_date = Ip_sheet[Col_A + str(Row)].value
            Ip_list.update({Ip_date: 1})
            #print(Ip_list)
            #print(date1)

    time.sleep(5)

 

这篇关于Python小程序(三):自动读取secure文件,并封禁异常IP地址的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!