Читать книгу Kali Linux Penetration Testing Bible - Gus Khawaja - Страница 77
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