Читать книгу Kali Linux Penetration Testing Bible - Gus Khawaja - Страница 75

Conditions

Оглавление

An if statement takes the following pattern:

if [[ comparison ]] then True, do something else False, Do something else fi

If you've been paying attention, you know that the best way to explain this pattern is through examples. Let's develop a program that pings a host using Nmap, and we'll display the state of the machine depending on the condition (the host is up or down):

#!/bin/bash #Ping a host using Nmap ### Global Variables ### #Store IP address IP_ADDRESS=$1 function ping_host(){ ping_cmd=$(nmap -sn $IP_ADDRESS | grep 'Host is up' | cut -d '(' -f 1) } function print_status(){ if [[ -z $ping_cmd ]] then echo 'Host is down' else echo 'Host is up' fi } ping_host print_status

The nmap command either returns an empty string text if the host is down or returns the value “Host is up” if it's responding. (Try to execute the full nmap command in your terminal window to visualize the difference. If so, replace $IP_ADDRESS with a real IP address.) In the if condition, the ‐z option will check if the string is empty; if yes, then we print “Host is down” or else we print “Host is up:”

root@kali:~# simpleping.sh 10.0.0.11 Host is down root@kali:~# simpleping.sh 10.0.0.1 Host is up

What about other condition statements? In fact, you can compare numbers, strings, or files, as shown in Tables 2.1, 2.2, and 2.3.

Table 2.1 Numerical Conditions

Equal [[ x ‐eq y ]]
Not equal [[ x ‐ne y ]]
Less than [[ x ‐lt y ]]
Greater than [[ x ‐gt y ]]

Table 2.2 String Conditions

Equal [[ str1 == str2 ]]
Not equal [[ str1 != str2 ]]
Empty string [[ ‐z str ]]
Not empty string [[ ‐n str ]]

Table 2.3 File/Directory Conditions

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 ]]
Kali Linux Penetration Testing Bible

Подняться наверх