Python小程序(三):自动读取secure文件,并封禁异常IP地址
Published on 2022-08-23 13:50 in 分类: 02.编程语言 / 01.Python with Diligent_Maple

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

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

    Python小白每周编写程序练习。之前编写的v1.0在pycharm中运行正常,但是在Linux中存在一点bug。现在更新为v1.2,在Linux上目前测试正常。

    复制代码
    #! python
    # -*- coding:utf-8 -*-
    # 时间:20220822
    # 版本:V1.2_20220824
    # 作者:ColoFly
    # 转载请注明出处及作者
    
    import os,re,time,datetime,openpyxl
    from collections import Counter
    
    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地址校验。
        sec_log = open(r'/var/log/secure', 'r', encoding='utf-8')
        sec_line = sec_log.readlines()
        file_location = 'prohibit_ip.xlsx'  # 定义存放文件名称
        workbook = openpyxl.load_workbook('prohibit_ip.xlsx')  # 加载表格簿
        Ip_sheet = workbook.active  # 读取表格
    
        matches = []
        for line in sec_line:
            if 'Failed password' in line:
                for Ip in IpRegex.findall(line):
                    matches.append(Ip[0])
    
        Ip_count = Counter(matches)
        print(Ip_count)
    
        Ip_list = {}
        for k,v in Ip_count.items():
            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})
    
            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')
                    os.system('iptables -A INPUT -p tcp -s ' + k + ' --dport 22 -j DROP')
                    print(k, datetime.datetime.now())
                    Ip_sheet[Col_A + str(Max_Row)] = k
                    Ip_sheet[Col_B + str(Max_Row)] = datetime.datetime.now()
                    workbook.save('prohibit_ip.xlsx')
    
        time.sleep(5)
    复制代码

     

    posted @   Diligent_Maple  阅读(65)  评论(0编辑  收藏  举报
    相关博文:
    阅读排行:
    · 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
    · 单线程的Redis速度为什么快?
    · SQL Server 2025 AI相关能力初探
    · AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
    · 展开说说关于C#中ORM框架的用法!
    点击右上角即可分享
    微信分享提示