Belajar Bash: for Loop

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”.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: