Shell Script: Speed of transfer of a hop using command Ping

292 views Asked by At

Create a shell script that relates the speed of transfer of a HOP between the machine and the IP chosen. Use the PING command and express the result in kB/sec.

!/bin/bash

I create a temporary file

touch info.txt;

I take the second line of command PING stopped after two seconds I post the results in the file.

ping -t 2 $1 | head -2 | tail -1 > info.txt;

I take bytes

cut -c -2 info.txt;

I take ms

cut -c 53-59 info.txt;

Now, how to make transformations in KB and in Sec?

Show result

echo "Result: .....";

I delete the file.

rm file.txt;
3

There are 3 answers

0
Cyrille Pontvieux On

You can do:

bytes=$(cut -c -2 info.txt)
ms=$(cut -c 53-59 info.txt)
echo "KiB: "$(($bytes/1024))
echo "Sec: "$(($ms/1000))
speed=$((1000*$bytes*1000/1024/$ms))
speed=$(echo $speed|sed -r 's/^(.*)(.{3})$/\1.\2/')
echo "Speed: $speed KiB/s"

This is of course considering 1 KiB = 1024 bytes, where KiB is usually used for KB.

0
Renjith On

RESULT=$(ping -t 2 -c 2 $1 | grep 'time=' | head -1 | sed 's/([0-9][0-9]).(time=)(.)(ms)/\1:\3/g')
echo "BYTES = ${RESULT%:}"
echo "SPEED = ${RESULT#
:}"



For the conversion part you might need to use python or perl. In bash it is not possible to calculate fractional numbers.

0
Liuk On

Thank you all! WORK!

touch info.txt;

ping -t 2 $1 | head -2 | tail -1 > info.txt;

bytes=$(cut -c -2 info.txt);

ms=$(cut -c 53-59 info.txt);

KB=$(echo "scale=5; $bytes /1024" | bc);

Sec=$(echo "scale=5; $ms /1000" | bc);

Speed=$(echo "scale=5; $KB/$Sec" | bc);

echo "Speed of HOP: $Speed KB/sec.";

rm info.txt;