How to get the percent of packets received from Ping in bash?
As always, there are many different ways to do this., but here's one option:
This expression will capture the percent digits from "X% packet loss"
ping -c 5 -q $host | grep -oP '\d+(?=% packet loss)'
You can then subtract the "loss" percentage from 100 to get the "success" percentage:
packet_loss=$(ping -c 5 -q $host | grep -oP '\d+(?=% packet loss)')
echo $[100 - $packet_loss]
how to extract ping parameters from a file in bash script
Try something like:
awk -F',|/' '/time/{x=$3$4}/rtt/{print x " " $5}' ping.txt | sed 's/[^0-9 .]*//g'
Output:
0 958 1.710
Get number of packets received by ping command in python
Here is my solution - just do stdout of ping command and analyze it.
def ping_ip(ip):
res = 0
current_os = platform.system().lower()
parameter = "-c"
if current_os == "windows":
parameter = "-n"
si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
command = ['ping', parameter, '4', ip]
process = subprocess.Popen(command, startupinfo=si, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
percentage = 0
f = process.stdout.read().decode('ISO-8859-1').split()
for x in f:
if re.match(r".*%.*", x):
strArr = []
strArr[:0] = x
strArr = strArr[1:-1]
listToStr = ''.join(map(str, strArr))
percentage = int(listToStr)
if percentage == 0:
res = 0 # 0% loss
elif percentage == 100:
res = 1 # 100% loss
else:
res = 2 # partial loss
return res
Ping reboot script percentage packet loss
ping
output on my system when there's 0% packet loss
and 100% packet loss
:
$ ping -c10 yahoo.com
PING yahoo.com (98.137.11.164): 56 data bytes
64 bytes from 98.137.11.164: icmp_seq=0 ttl=53 time=75.890 ms
... snip ...
64 bytes from 98.137.11.164: icmp_seq=9 ttl=53 time=75.553 ms
--- yahoo.com ping statistics ---
10 packets transmitted, 10 packets received, 0% packet loss
round-trip min/avg/max/stddev = 73.983/76.589/78.678/1.682 ms
$ ping -c10 yahoo.com
PING yahoo.com (74.6.143.25): 56 data bytes
--- yahoo.com ping statistics ---
10 packets transmitted, 0 packets received, 100% packet loss
It may make more sense to search for the string packet loss
and then take the 7th (white space delimited) field, eg:
ping -c10 "host" | awk '/packet loss/{print int($7+0)}'
When applied to the 2x scenarios above this generates 0
and 100
, respectively.
NOTES:
- in the
awk
code the$7+0
has the effect of stripping off trailing non-numeric characters (eg,%
) - in the
awk
code theint()
insures we only generate an integer (in caseping
were to ever generate a float/real value);bash
only works with integers so we need to make sure we only pass an integer back to the calling process - OP may want additional logic to handle a
ping
command that goes walkabout, eg, generates an error (ping: unknown host
), generates nothing, hangs, etc
how can i improve my sed command to extract data form ping log file?
Let's assume:
- The packet loss percentage is always found in lines ending with
NUM% packet loss
. - The date and time are always found in lines ending with
data bytes
.
Then, with GNU sed (tested on the two complete records you show):
$ sed -nE '/packet loss$/{s/.*\s([0-9]+%) packet loss$/\1/;h}
/data bytes$/{s/(.{24}).*/\1/;G;s/\n/, /;p}' sample.log
jue 08 abr 2021 13:35:35, 0%
jue 08 abr 2021 13:37:21, 1%
shell script to check ping packet loss & avg latency on AIX
Try this:
ping ... | awk '/packet loss/{x="Loss:" $7} /round-trip/{x="Trip:" $4} END{print x}'
If it sees a line with "packet loss" in it, it creates a string x
with the packet loss percentage. If it sees a line with "round-trip" it overwrites the string x
with the round trip time. At the end, it prints whatever the string x
is set to.
In the light of your comments...
awk '/packet loss/ && /100/{x="Loss: " $7} /round-trip/{split($4,a,/\//);x="Ave: " a[2]} END{print x}'
So, now the "packet loss" line must also contain "100" before we pick it up. And the 4th field of the "round-trip" line is split into an array a[]
using /
as separator, then we take the second element of a[]
as the average and store that in our output string x
.
Bash ping output in csv format
Since the second line of the pingOutput was never processed (the loop ended before) the action of adding the -1 to the output was never performed.
Due to this problem I decided to capture the percentage of failure and act when no packets were returned (100%), I also simplified some expressions you used initially.
I investigated the script and came up with the following solution:
#!/bin/bash
declare site=''
declare result=''
declare prctg=''
[[ "$1" == "www."* ]] && site="$1" || site="www.$1"
result="$site"
pingOutput=$(ping $site -c10 -i0.2 -q| tail -n2)
fl=true
while IFS= read -r line
do
# !!! The problem is here, the if statement is not working properly and I do not know why !!!
echo $line
if [ "$fl" == "true" ]
then
prctg=$(echo "$line" | grep -Po "[0-9]{0,3}(?=%)")
result="$result $prctg"
fl=false
fi
if [ "$prctg" == "100" ]
then
result="$result -1 -1 -1 -1"
else
result="$result $(echo "$line" | cut -d' ' -f4 | sed -r 's/\// /g')"
fi
done <<< "$pingOutput"
echo "$result"
extract values of ping message
Start by getting each line of the string:
String[] lines = pingResult.split("\n");
Then, loop and use substring.
for (String line : lines) {
if (!line.contains("time=")) continue;
// Find the index of "time="
int index = line.indexOf("time=");
String time = line.substring(index + "time=".length());
// do what you will
}
If you want to parse to an int
, you could additionally do:
int millis = Integer.parseInt(time.replaceAll("[^0-9]", ""));
This will remove all non-digit characters
You can do something similar for the percentage:
for (String line : lines) {
if (!line.contains("%")) continue;
// Find the index of "received, "
int index1 = line.indexOf("received, ");
// Find the index of "%"
int index2 = line.indexOf("%");
String percent = line.substring(index1 + "received, ".length(), index2);
// do what you will
}
Related Topics
How to Execute Shell Builtin from Scala
Nm Reports Symbol Is Defined But Ldd Reports Symbol Is Undefined
Difference Between Arm-None-Eabi and Arm-Linux-Gnueabi
Openssl/Rsa - Using a Public Key to Decrypt
Cloudera Manager Failed to Authenticate: Exhausted Available Authentication Methods
Can 'Find' or Any Other Tool Search for Files Breadth-First
How to Answer Yes in Bash Script
Embedded Linux - Mechanism for Deploying Firmware Updates
How to Send Signal from One Program to Another
Getting Following Error After The Command Sudo Apt-Get Update on Ubuntu 16.04
Graphics Card Memory and Virtual Address Space of a Process
Implicit Declaration of Function 'Create_Proc_Entry'
Eclipse Doesn't Use The Path Set in .Bashrc
Yocto Bitbake Script Not Displaying Echo Statement
Short Command to Find Total Size of Files Matching a Wild Card