In computer programming, loops help us with repetitive tasks that we need to run until a certain
criteria is met. Iteration is particularly useful for penetration testers, so we recommend paying very
close attention to this section.
In Bash, the two most predominant loop commands are for and while. We will take a look at both.
For loops are very practical and work very well in Bash one-liners. This type of loop is used to
perform a given set of commands for each of the items in a list. Let’s briefly look at its general
syntax:
1 | for var-name in <list> |
The for loop will take each item in the list (in order), assign that item as the value of the variable varname, perform the given action between do and done, and then go back to the top, grab the next
item in the list, and repeat the steps until the list is exhausted.
Let’s take a look at a more practical example that will quickly print the first 10 IP addresses in the
10.11.1.0/24 subnet:
1 | kali@kali:~$ for ip in $(seq 1 10); do echo 10.11.1.$ip; done |
In this Bash one-liner, we used the seq command to print a sequence of numbers, in
this case the numbers one through ten. Each number is then assigned to the ip variable, and then
each IP address is displayed to the screen as the for loop runs multiple times, exiting at the end of
the sequence.
Another way of re-writing the previous for loop involves brace expansion using ranges. Brace
expansion using ranges is written giving the first and last values of the range and can be a sequence
of numbers or characters. This is known as a “sequence expression”:
1 | kali@kali:~$ for i in {1..10}; do echo 10.11.1.$i;done |
There is a lot of potential for this type of loop. Displaying IP addresses to the screen may not seem
very useful, but we can use the same loop to run a port scan using nmap (which we discuss in
detail in another module). We can also attempt to use the ping command to see if any of the IP
addresses respond to ICMP echo requests, etc.