for Loop Example

by mike on April 6, 2011

The purpose of this exercise is to write a number of for loops to be able to understand how to implement them effectively.

1.  Create a script called defense.sh in /opt/scripts
The purpose of the script is to configure the firewall to drop known zombie networks.

#!/bin/bash
IP=/opt/scripts/banned

for i in $(awk '{print}' < "$IP" )
do
echo $i
iptables -A INPUT -p tcp -s $i -j DROP
done
exit 0

The script takes a list of IP Addresses in a file and uses awk to print each IP from the file into the variable $i.  Then an iptables command employs the “$i” variable to drop each of the IP Addresses on the INPUT chain.  The “-p tcp” limits the drop to TCP protocol and the “-s” indicates the source.  The IP is dropped with the jump “-j” to DROP.

Create a file with known zombie networks.  This file is actually maintained by Spamhaus.org (http://www.spamhaus.org/xbl/).  This is a short sample.

banned file with IPs
24.190.78.101
38.101.148.126
41.206.45.202
58.0.0.0/8
59.107.0.0/17
59.108.0.0/15
59.110.0.0/15
59.151.0.0/17
59.155.0.0/16
59.172.0.0/15

Test the script  output with :
iptables -L -n

Chain INPUT (policy ACCEPT)
target     prot opt source               destination
RH-Firewall-1-INPUT  all  –  0.0.0.0/0            0.0.0.0/0
DROP       tcp  –  24.190.78.101        0.0.0.0/0
DROP       tcp  –  38.101.148.126       0.0.0.0/0
DROP       tcp  –  41.206.45.202        0.0.0.0/0
DROP       tcp  –  58.0.0.0/8           0.0.0.0/0
DROP       tcp  –  59.107.0.0/17        0.0.0.0/0
DROP       tcp  –  59.108.0.0/15        0.0.0.0/0
DROP       tcp  –  59.110.0.0/15        0.0.0.0/0
DROP       tcp  –  59.151.0.0/17        0.0.0.0/0
DROP       tcp  –  59.155.0.0/16        0.0.0.0/0
DROP       tcp  –  59.172.0.0/15        0.0.0.0/0

2.  List executable files in a directory, create a file called dir.sh

#!/bin/bash
for i in *
do
if [ -f "$i" -a -x "$i" ]
then
echo "Executable file $i "
fi
done

This script will list executable files in a directory.  Note the for loop will loop through all files and only print those which are files “-f” and “-a” are executable “-x”.

{ 3 comments }

Doyle Young April 7, 2011 at 3:24 pm

I was wondering why you used awk ‘{print}’ < "$IP" instead of cat "$IP"? I ran a couple quick tests and can't figure out any difference. Is there an advantage to the awk approach?

Thanks

mike April 12, 2011 at 10:25 pm

One major advantage of awk is that you can cut out fields that you can use elsewhere in the script. cat is a command that often leads you down the path of wasting resources as well. Nothing wrong with cat but many other options allow you to use resources more effectively.

Gerry April 7, 2011 at 7:04 pm

Please show how you get the XBL list. If via cron, please show your entry

Comments on this entry are closed.

Previous post:

Next post: