Sunday, July 10, 2016

Diving into Linux Bash

Linux operating system has everything any hacker needs. Bash with all the tools that can be combined to create beautiful pyramid of fast actions will be the core of this blog. Let's log on to Raspberry PI and begin the adventure.

Send 10 ping packets to Using bash tools extract the slowest and fastest response. 

Ping uses ICMP echo (type 8) and echo reply (type 0) messages. As long as firewall between the sender and the receiver do not block those messages, using ping utility we can check if the target system is alive (at least at the layer 3 of OSI model)

First how to send just 10 ping packets using Linux Bash?

pi@tron:~ $ ping -c10 > ping.txt

Linux sends ping until you stop it with CTRL-C. In order to send a number of ping packets option -c (count) followed by number 10 will send only 10 packets. Then it stops. 

The result of the ping is going to be sent to a file called 'ping.txt'

Let's see the results:

pi@tron:~ $ cat ping.txt

The output is nicely placed in columns separated by a 'space' character. There are 9 columns of output. This can be used to our advantage.

First I am going to get rid of the output that does NOT have 'ms' leaving only what I want:

pi@tron:~ $ grep "ms" ping.txt

Then, using 'awk' utility I will print out the last two columns (awk breaks each line into variables $1 = 64, $2 = bytes $3 = from, etc.).

pi@tron:~ $ grep "ms" ping.txt | awk '{ print $8,$9}'

There is some garbage left at the end of the output now. So, let's get rid of it:

pi@tron:~ $ grep "ms" ping.txt | awk '{ print $8,$9}' | grep "ms"

Now, I am only interested in displaying the number and ms:

pi@tron:~ $ grep "ms" ping.txt | awk '{ print $8,$9}' | grep "ms" | cut -d "=" -f2

Sort them from lowest to highest delay:

pi@tron:~ $ grep "ms" ping.txt | awk '{ print $8,$9}' | grep "ms" | cut -d "=" -f2 | sort -n

And finally using 'head -1', display the lowest delay value and 'tail -1' display the highest delay value:

pi@tron:~ $ grep "ms" ping.txt | awk '{ print $8,$9}' | grep "ms" | cut -d "=" -f2 | sort -n | head -1
5.30 ms
pi@tron:~ $ grep "ms" ping.txt | awk '{ print $8,$9}' | grep "ms" | cut -d "=" -f2 | sort -n | tail -1
5.68 ms
pi@tron:~ $