• 使用 python 检测泛洪攻击的案例


    使用 python 检测泛洪攻击的案例

    本案例只使用python标准库通过执行命令来监控异常请求, 并封锁IP, 不涉及其他第三方库工具.

    import os
    import time
    from collections import Counter
    
    
    # 1、update 命令, 采集CPU的平均负载
    def get_cpu_load():
        """
        uptime 命令获取系统开机时间和cpu负载, 比如:
            04:02:00 up 1 day,  3:49,  1 user,  load average: 0.71, 0.48, 0.46
        利用awk命令来筛选出CPU负载:
            -F 设置拆分数据的分隔符 ': ', 如果不设置默认以空格作为分隔符
            '{print $2}' 表示打印第二列数据
        """
        cpu_load = os.popen("uptime | awk -F ': ' '{print $2}' | awk -F ',' '{print $1}'").read()
        cpu_load = float(cpu_load)
        return cpu_load
    
    
    # 2、netstat 命令, 采集 tcp 的连接数量
    def get_conn_count():
        """
        统计所有tcp连接数量
            -a 列出所有, -n 以数字形式显示端口, -t tcp
            wc -l 统计行数
        """
        netstat = os.popen('netstat -ant | wc -l').read()
        return int(netstat)
    
    
    # 3、ss命令, 采集socket统计信息,
    """
    ss命令比netstat命令更详细, 速度更快
    端口队列默认大小是128, 当 Recv-Q 大于等于 Send-Q 时表示队列满了, 端口存在大量请求
    """
    def get_queue_size():
        """
        统计当前的队列情况
            -l 监听状态, -n 以数字显示, -t tcp
        """
        # ss -lnt | grep :80 | awk '{print $2}' # 第二列是 Recv-Q
        # ss -lnt | grep :80 | awk '{print $3}' # 第三列是 Send-Q
        sslnt = os.popen("ss -lnt | grep :80").read()
        recv_q = int(sslnt.split()[1])
        send_q = int(sslnt.split()[2])
        return recv_q, send_q
    
    
    # 4、netstat 命令, 采集连接数量最多的IP地址
    def get_most_ip():
        """
        获取当前连接数量最多的IP地址
        """
        # 获取所有访问 80 端口的ip添加到列表中
        result = os.popen('netstat -ant | grep :80').read()
        line_list = result.split('\n')
        ip_list = []
        for line in line_list:
            try:
                temp_list = line.split()
                ip = temp_list[4].split(':')[0]
                ip_list.append(ip)
            except Exception as e:
                pass
        # 统计列表中出现最多的ip
        cnt = Counter(ip_list)
        # most_common(n) 返回出现次数最多的前n项元组组成的列表
        t = cnt.most_common(1)
        return t[0][0]
    
    
    # 5、firewall-cmd 命令, 防火墙封锁IP地址
    def firewall_ip(ip):
        """
        使用防火墙封锁ip
        :param ip: 封锁目标ip
        """
        result = os.popen(f"firewall-cmd --add-rich-rule='rule family=ipv4 source address={ip} port port=80 protocol=tcp reject'").read()
        if 'success' in result:
            print(f"成功封锁 {ip}.")
        else:
            print(f"封锁失败.")
    
    if __name__ == '__main__':
        while 1:
            cpu = get_cpu_load()
            conn = get_conn_count()
            recvq, sendq = get_queue_size()
            print(f"CPU-Load: {cpu}, TCP Conn: {conn}, TCP Queue: {recvq, sendq}")
    
            # 对采集到的数据进行判断,并进行预警提醒, 封锁ip
            if cpu > 55 and conn > 500 and recvq > sendq - 10:
                ip = get_most_ip()
                print(f"预警,可疑IP:{ip}.")
                firewall_ip(ip)
    
            time.sleep(5)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
  • 相关阅读:
    js 中 Map 和 Set 的用法及区别
    网课搜题公众号接口怎么对接?
    Git_02_查看本地未推送的commit记录
    深入探讨Function Calling:实现外部函数调用的工作原理
    python字符串转list,多维度,支持float,并保持原数据结构
    四、Spring Boot 整合 Web开发(1)
    java计算机毕业设计springboot+vue股票交易模拟系统
    求过去半年内连续30天以上每天都有1000元以上成交的商铺
    【蓝桥杯集训100题】scratch指令移动 蓝桥杯scratch比赛专项预测编程题 集训模拟练习题第14题
    Linux高并发服务器开发(六)线程
  • 原文地址:https://blog.csdn.net/bua200720411091/article/details/133614323