In this lecture, I'll show you a real-life example of a script that uses a for loop to drop the packets 1
from a list of remote IP addresses. 2
This can be very useful because you'll find in the logs lots of IP addresses that send you spam, scan your network 3
or do other things and want to block them. 4
Let's take a look at the script we've created in a previous lecture, the one that drops the packets 5
from a single IP address. 6
This is the script. 7
To drop the packets from a list of IP addresses, I'll iterate over the list with IP addresses and execute 8
the iptables command for each IP in the list. 9
Logic, isn't it? 10
So I'm creating the script: drop_ips.sh 11
I'm creating a variable that will contain the list of IP addresses to drop, so DROPPED_IPS= 12
and the IP addresses as a string separated by spaces. 13
And I am iterating over the list, dropping IP after IP so: for ip in $DROPPED_IPS 14
do and done and between do and done echo "Dropping packets from $ip" and the iptables rule that 15
will drop the packets so iptables -I input -s the source IP address $ip -J DROP 16
Use the exact letter case you are seeing in my example and that's all. 17
I'm saving the file and I'm setting the execution permission. 18
I'm testing the connection to an IP address from the list, so ping 8.8.8.8 19
and it's working. 20
OK, the name of the script is drop_ips, ending in s, and I'm running the script as root so sudo 21
drop_ips.sh 22
And the ping has stopped; all the packets from these 3 IP addresses are dropped. 23
If you want to drop the packets for another IP address, just add that IP address to the list. Let's see 24
another variation of the same challenge. 25
Instead of writing the IP address in the script file, I want to have a dedicated file with the IP addresses 26
that will be denied. First I am creating the file vim ips.txt and I'm adding a few random IP addresses 27
there, 28
one IP per line. 29
OK, that's enough, I'm saving the file. I'm copying the previous script as another file so that you 30
have both examples. 31
Instead of iterating over the list of IP addresses, I perform a command substitution; I'm running cat 32
and the file that contains the IP addresses and iterate over the output of the command. 33
At the end of the day, I'll iterate over the list of IP addresses. 34
I'm removing this line and for ip in and the command substitution. 35
$(cat ips.txt) The file is in the current directory. 36
And that's all! I'm saving the file and running it as root. 37
Great! It's working!