File exists? |
[[ ‐a filename ]]
|
Directory exists? |
[[ ‐d directoryname ]]
|
Readable file? |
[[ ‐r filename ]]
|
Writable file? |
[[ ‐w filename ]]
|
Executable file? |
[[ ‐x filename ]]
|
File not empty? |
[[ ‐s filename ]]
|
Loops
You can write loops in two different ways: using a while
loop or using a for
loop. Most of the programming languages use the same pattern for loops. So, if you understand how loops work in Bash, the same concept will apply for Python, for example.
Let's start with a while
loop that takes the following structure:
while [[ condition ]] do do something done
The best way to explain a loop is through a counter from 1 to 10. We'll develop a program that displays a progress bar:
#!/bin/bash #Progress bar with a while loop #Counter COUNTER=1 #Bar BAR='##########' while [[ $COUNTER -lt 11 ]] do #Print the bar progress starting from the zero index echo -ne "\r${BAR:0:COUNTER}" #Sleep for 1 second sleep 1 #Increment counter COUNTER=$(( $COUNTER +1 )) done
Note that the condition ( [[ $COUNTER ‐lt 11]]
) in the while
loop follows the same rules as the if
condition. Since we want the counter to stop at 10, we will use the following mathematical formula: counter<11
. Each time the counter is incremented, it will display the progress. To make this program more interesting, let it sleep for one second before going into the next number.
On the other hand, the for
loop will take the following pattern:
for … in [List of items] do something done
We will take the same example as before but use it with a for
loop. You will realize that the for
loop is more flexible to implement than the while
loop. (Honestly, I rarely use the while
loop.) Also, you won't need to increment your index counter; it's done automatically for you:
#!/bin/bash #Progress bar with a For Loop #Bar BAR='##########' for COUNTER in {1..10} do #Print the bar progress starting from the zero index echo -ne "\r${BAR:0:$COUNTER}" #Sleep for 1 second sleep 1 done
File Iteration
Here's what you should do to simply read a text file in Bash using the for
loop:
for line in $(cat filename) do do something done
In the following example, we will save a list of IP addresses in a file called ips.txt
. Then, we will reuse the Nmap ping program (that we created previously) to check whether every IP address is up or down. On top of that, we will check the DNS name of each IP address:
#!/bin/bash #Ping & get DNS name from a list of IPs saved in a file #Prompt the user to enter a file name and its path. read -p "Enter the IP addresses file name / path:" FILE_PATH_NAME function check_host(){ #if not the IP address value is empty if [[ -n $IP_ADDRESS ]] then ping_cmd=$(nmap -sn $IP_ADDRESS| grep 'Host is up' | cut -d '(' -f 1) echo '------------------------------------------------' if [[ -z $ping_cmd ]] then printf "$IP_ADDRESS is down\n" else printf "$IP_ADDRESS is up\n" dns_name fi fi } function dns_name(){ dns_name=$(host $IP_ADDRESS) printf "$dns_name\n" } #Iterate through the IP addresses inside the file for ip in $(cat $FILE_PATH_NAME) do IP_ADDRESS=$ip check_host done
If you have followed carefully through this chapter, you should be able to understand everything you see in the previous code. The only difference in this program is that I used Tab spacing to make the script look better. The previous example covers most of what we did so far, including the following:
User input
Declaring variables
Using functions
Using if conditions
Loop iterations
Printing to the screen
Summary
I hope you have practiced all the exercises in this chapter, especially if you're new to programming. A lot of the concepts mentioned will apply to many programming languages, so consider the exercises as an opportunity to learn the basics.
I personally use Bash scripting for small and quick scenarios. If you want to build more complex applications, then you can try doing that in Python instead. Don't worry! You will learn about Python at the end of this book so you can tackle any situation you want in your career as a penetration tester.
Finally, this chapter covered a lot of information about Bash scripting. However, there is a lot more information than what is in this chapter. In practice, I use internet search engines to quickly find Bash scripting references. In fact, you don't need memorize everything you learned in this chapter. Remember that this book is a reference on which you can always rely to remember the syntaxes used in each case.
Конец ознакомительного фрагмента.
Текст предоставлен ООО «ЛитРес».
Прочитайте эту книгу целиком, купив полную легальную версию на ЛитРес.
Безопасно оплатить книгу можно банковской картой Visa, MasterCard, Maestro, со счета мобильного телефона, с платежного терминала, в салоне МТС или Связной, через PayPal, WebMoney, Яндекс.Деньги, QIWI Кошелек, бонусными картами или другим удобным Вам способом.