A Bash script is a plain text file that contains a series of commands. These commands are a mixture of commands we would normally type ourselves on the command line (such as ls or cp for example) and commands we could type on the command line but generally wouldn’t.
- script writing
- for loops
Command that pings Google’s IP address one time:
[email protected]:~# ping 188.8.131.52 -c 1 PING 184.108.40.206 (220.127.116.11) 56(84) bytes of data. 64 bytes from 18.104.22.168: icmp_seq=1 ttl=128 time=3.65 ms --- 22.214.171.124 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 3.653/3.653/3.653/0.000 ms
The objective of exercise: Grab the IP address from the line containing the text “64 bytes”
- First, we are going to be making use of a tool called grep to retrieve the entire line as seen below
[email protected]:~# ping 126.96.36.199 -c 1 | grep “64 bytes” 64 bytes from 188.8.131.52: icmp_seq=1 ttl=128 time=3.67 ms
- Next up, we are going to be using a tool named cut on top of grep to be able to get only the IP address which is our final objective
[email protected]:~# ping 184.108.40.206 -c 1 | grep “64 bytes” | cut -d “ “ -f 4 220.127.116.11:
- Now we have a small little problem, we have a semicolon at the end of the output. If we were to use that output to ping the IP that wouldn’t work due to the extra character. Let's take a look at how we can further edit the output using a tool named tr
[email protected]:~# ping 18.104.22.168 -c 1 | grep “64 bytes” | cut -d “ “ -f 4 | tr -d “:” 22.214.171.124
The objective of the script: Create a ping sweeping script similar to [nmap -sn]
- Now that we have all that information, let's move on to creating a simple bash script that will ping sweep a subnet for alive hosts!
[email protected]:~/scripts# cat pingsweep.sh #!/bin/bash if [ "$1" == "" ] then echo"" echo"" cat /root/scripts/sign echo"" echo"" echo "You cant leave your network address blank :(" echo "It should look something like: ./pingsweep.sh 192.168.1" echo"" echo"" else echo"" echo"" cat /root/scripts/sign echo"" echo"" cat /root/scripts/process echo "" echo "The following are the alive hosts....." for ip in `seq 1 254`;do ping -c 1 $1.$ip | grep "64 bytes" | cut -d " " -f 4 | tr -d ":" & done fi echo "" echo ""
- The first if loop is to check if the user had entered the variable, in our case the network address.
- If that loop meets its criteria we then proceed to iterate through the whole subnet by adding values from 1 all the way to 254 behind the network address provided by the user.
- If there is no input entered by the user, the script will terminate, else it will iterate through the subnet and come up with the hosts that are alive!
- Use case 1: user ran the script without an argument
- Use case 2: user ran the script with a valid network address as the argument