Search code examples
linuxscriptingdebiandenial-of-service

Script to count number of incoming packets per second?


Currently, I am trying to write a script that will run upon startup (Debian Linux), and count the number of incoming packets per second every ten seconds. The goal of this is to study different ways to mitigate DoS attacks, but I don't really know how to setup this base function of the script. I have done quite a bit of research into the best way to accomplish this, but really cannot find what I'm looking for. Since I'm a beginner in Linux scripting, can someone describe the process to accomplish this in layman's terms? Thank you so much!


Solution

  • Try this :

    #!/bin/bash
    
    old_packets=0
    
    while true; do
        packets=$(awk '$1 == "eth0:"{print $3}' /proc/net/dev)
        if ((old_packets)); then
            clear
            echo "$(bc <<< "($packets - $old_packets) / 10") packets/seconds"
        fi
        old_packets=$packets
        sleep 10
    done
    

    where eth0 is the targeted interface.

    Edit:

    from comments, if you want to disable eth0 if the rate exceed 20 packets/seconds :

    #!/bin/bash
    
    old_packets=0
    
    while true; do
        packets=$(awk '$1 == "eth0:"{print $3}' /proc/net/dev)
        if ((old_packets)); then
            clear
            # the variable rate contains the packets/seconds
            rate=$(bc <<< "($packets - $old_packets) / 10")
            echo "$rate packets/seconds"
            if ((rate>20)); then
                ip link set eth0 down
            fi
        fi
        old_packets=$packets
        sleep 10
    done
    

    If you want to run this script at startup, you can edit your /etc/rc.local file, it's executed at the end of boot process.