In this task we wanted to collect all ip addresses on our network by pinging them and storing them in a file.
Next we create a fiel named ip.txt to store our ip addresses
Since we only want the ip addresses to be stored so we can use th e grep command to get that specific line. Combining with the cut command we can extract only the required ip address.
Lets break down this command: cat ip.txt | grep "64 bytes" | cut -d " " -f 4 | tr -d ":"
cat ip.txt: Fetches the content ofip.txtfile|: joins the commands togethergrep "64 bytes": grabs the line containing "64 bytes"cut -d " " -f 4: trims down the spaces between the words and-f 4tells to jump to the fourth word (which is in this case the ip address 192.168.248.128)tr -d ":": trims the colon after the ip address
Now since we know how to grab an ip address through ping command we need to create a bash script to automate this and get all available ip addresses on the network
So we start by creating the file and opening it in mousepad using the command:
mousepad ipsweep.sh
So lets start with creating the script. The first part of every bash script is this line : #!/bin/bash
After that we start writing our code step by step:
-
First we add that command which we used earlier to get the ip address:
ping 192.168.248.128 -c 1 | grep "64 bytes" | cut -d " " -f 4 | tr -d ":" -
Since we know that we have a subnet mask of 255.255.255.0 so we only want to continously go through all 255 combination of the fourth portion of our IP address (192.168.248.128) i.e,
.128part.So we modify the ip address in command and suppose a
variablein its place ($ip). -
In order to itterate over this value we need a loop. We are going to use a for loop in this case which has the follwoing syntax:
for $<variable_name> in `seq <range>; do <command to be repeated> done fiHere
$ipwill:- Start from $ip = 1
- End at $ip = 254
So the first address we will itterate over will be:
192.168.248.1This will go on to change the value to .2 , .3 ... upto .254 and end at the ip:
192.168.248.254 -
In order to make this more robust we change the hard coded first part of the ip address (network part) to take in user input
Here we have replaced:
192.168.248.with$1(user input)
-
In order to ensure that the user input is not empty we add the checking condition before the loop with an
if-elsestatement -
In order to speed up the process of looping we add an
&at the and of the command:ping -c 1 $1.$ip | grep "64 bytes | cut -d " " -f 4 | tr -d ":" & -
Now hit
Ctrl + Sto save this file
In order tp run a bash script we have the following syntax:
./<filename>
A loop in programming is used to do the same task repeatedly
A variable is a value which we want to change as the program proceeds further. In its contrary if we want to make a vakue fixed we use a constant
If - else block or ladder is used to check conditions in programming




.png)
.png)
.png)
.png)
.png)
.png)
.png)