linuxbashiptablesnmap

Bash Script Block All Apple Devices


I am trying to create a shell script to block all apple devices on my network. I am using nmap for os detection. What I have so far is this:

while (true) do
    nmap -O -T4 -p 22,80 -v 172.20.0.0/24 | grep -B9 'OS details: Apple' | \
        grep 'Nmap scan report for' | cut -f4 -d'r' | cut -f2 -d' ' | \
        iptables -i wlan0 -A INPUT -j DROP -s
    sleep 10
done

Is there a way to simplify this at all so there is less grepping and cutting involved? Also, this script will run into errors if there are more than one or zero apple devices found on the network. Is it possible to add logic for that?


Solution

  • Yes, of course it is possible. You can use perl/awk to simplify the script a lot.

    Also, I'm not sure that your script is correct at the moment. You have a pipe that write addresses to iptables, but iptables doesn't work this way.

    If you want to run iptables for each address that is produced by nmap, you can read the addresses using read to some variable (in my example ADDR) and then use the variable in iptables:

    while (true) do
        nmap -O -T4 -p 22,80 -v 172.20.0.0/24 | grep -B9 'OS details: Apple' | \
            grep 'Nmap scan report for' | cut -f4 -d'r' | cut -f2 -d' ' | \
            while read ADDR
            do
              iptables -i wlan0 -A INPUT -j DROP -s $ADDR
            done
        sleep 10
    done