Storing Value from a Parsed Ping

Storing value from a parsed ping

Use subprocess.check_output if you want to store the output in a variable:

from subprocess import check_output
l = check_output("ping -c 1 sitename | awk -F = 'FNR==2 {print substr($4,1,length($4)-3)}'", shell=True)
print l

Related: Extra zero after executing a python script

Parsing output from ping

Is this what you want?

import re
import subprocess
import sys

from tabulate import tabulate

def main():
address = sys.argv[1]
pingthis = ['ping', '-c', '1', address]
r = (
subprocess
.run(
pingthis,
stdout=subprocess.PIPE,
check=True,
)
.stdout
.decode('utf-8')
)
table = tabulate(
[[address, (re.search(r'time=(\d+)', r).group(1))]],
headers=["IP", "TimeToPing (ms)"],
tablefmt="simple",
)
print(table)

if __name__ == "__main__":
main()

Output for python main.py 8.8.8.8

IP         TimeToPing (ms)
------- -----------------
8.8.8.8 14

Pinging Hostnames from a Parsed File and Logging in Batch

You can't filter the output for a certain string and expect the complete output (eliminating unwanted parts is the very reason for filtering).

To accomplish your goal, you need a temporary file (the complete output) and filter that file, so you have both variants (filtered and unfiltered) (suboptimal, but well...):

ping -n 1 "%%i" >"%temp%\temp.tmp"
find /I "timed out" "%temp%\temp.tmp" >nul && set "status=Fail" || set "status=Pass"
type "%temp%\temp.tmp" >> "C:\Users\___\Downloads\pingLOG.txt"
echo %status% >> "C:\Users\___\Downloads\pingLOG.txt"

Parse out time portion from ping results in Java

Try this:

Pattern pattern = Pattern.compile("time=(\\d+)ms");
Matcher m = null;
while ((inputLine = in.readLine()) != null) {
m = pattern.matcher(inputLine);
if (m.find()) {
System.out.println(m.group(1));
}
}

Which outputs the millisecond value from the captured patterns.

Python - How to Output Ping results to Pandas DataFrame Object

Here's my solution to the problem:

# Import packages
import os
import pandas as pd
import numpy as np

# Define ping target, ping the target, and then store results as string
ping_target = 'google.com'
results = os.popen('ping ' + ping_target).read()
print(results)

# Extract the times from the results string
times = []
for i in range(4):
timeIdx = results.index('time')
time = results[timeIdx+5:timeIdx+7]

results = results[timeIdx+10:]

times.append(time)

# Put data into pandas DataFrame
d = {'PingNum': np.arange(1,5), 'PingTime_ms': times}
df = pd.DataFrame(data=d)

The initial "results" variable looks like this

Ping results

There's no need for those fancy libraries, the os library will do the job!

NOTE: This solution is good for Windows, since the number of ping times returned is always 4.

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
}

How can I store the Tnsping output in a variable?

You can store the output of a command using command substitution.

However, you said you wanted to check the result. If you store that string output you would need to parse it to only look for 'OK' (since the ping time might differ), and deal with the banner info etc. (though that is relatively easy).

It would be simpler to look at the return code from from the tnsping command rather than its output:

tnsping myDB
echo $?

You can test the value of $?. If the ping was OK then it will be zero; otherwise it will be 1.

You haven't said what you want to do with the test result. If you want to show the error (if there is one) and nothing if it worked, you could combine both:

RESULT=$( tnsping myDB )
if [[ $? -ne 0 ]]; then
printf "Ping failed, output was\n\n"
printf "%s\n" "${RESULT}"
fi

how can I extract Average in this each ping result and store in file

After doing some research I found out that using subprocess.run and then getting the returncode you dont get the output but only the return code so usually 0 for a successfull run with no error.
If you want to get the output of the process you have to use subprocess.Popen and then communicate.
Then if you only want the average you have to do some string manipulation with the output to only get the number after "Average".
Here's an exemple:

def ping(host):
output = subprocess.Popen(["ping", host, "-n", "1"], stdout=subprocess.PIPE).communicate()[0]
words = str(output).split(sep=" ")
average = words[words.index("Average")+2].split("ms")[0]
ip_list.append(host+ ' '+ average)


Related Topics



Leave a reply



Submit