1

before writing this post, I tried to do it by myself but give up.

I read this one and this but I could not get it

This is the code to show us latency data:

import os
x = os.system("ping 192.168.1.1")

The output is:

PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.
64 bytes from 192.168.1.1: icmp_seq=1 ttl=64 time=2.47 ms
64 bytes from 192.168.1.1: icmp_seq=2 ttl=64 time=2.97 ms
64 bytes from 192.168.1.1: icmp_seq=3 ttl=64 time=3.02 ms
64 bytes from 192.168.1.1: icmp_seq=4 ttl=64 time=2.74 ms
64 bytes from 192.168.1.1: icmp_seq=5 ttl=64 time=2.74 ms
64 bytes from 192.168.1.1: icmp_seq=6 ttl=64 time=2.08 ms

--- 192.168.1.1 ping statistics ---
6 packets transmitted, 6 received, 0% packet loss, time 5007ms
rtt min/avg/max/mdev = 2.087/2.674/3.020/0.319 ms

I would like to only save these data like this figure enter image description here

4
  • 1
    hmm, how did you get the second row? looks like it's for pinging the same server Commented Dec 9, 2021 at 4:21
  • 1
    I only ran it twice, you can skip it. Commented Dec 9, 2021 at 4:23
  • 1
    If you want to redirect the output of a command to a file I suggest you use the subprocess module. You will still need to reformat into into CSV format. Commented Dec 9, 2021 at 6:01
  • 2
    Thank you for your suggestion. I have already started using it. Commented Dec 9, 2021 at 6:15

1 Answer 1

2

Use os.popen() rather than the os.system() function to return the output to a variable.

os.popen() executes the task in background and return the output, while os.system() execute the task in a terminal.

Here is the full code to extract the ip statistics to a .csv file (Linux only) :

import os

ip = "192.168.1.1"

x = os.popen("ping -c 4 "+ip).read()

print (x)

x = x.splitlines()

x = x[len(x)-1]


x = x.replace("rtt min/avg/max/mdev = ","")

x = x.replace(" ms" , "")
x = x.replace("/" , ",")

x = ip +","+ x

file = open("newfile.csv","w")
file.write("PING,min,avg,max,mdev\n")
file.write(x)
file.close()
print(x)
print(".csv created successfully")

Note : The x = os.popen("ping -c 4 "+ip).read() command represents that the number of times the ping will occur and end is 4(written after ping -c ). The number can replaced by any other number, as needed. But this doesn't cause much changes to the result.

Sign up to request clarification or add additional context in comments.

4 Comments

Sorry, It doesn't work for me.
What output you are getting ?
It is nothing FOR first print (x).
The first code was specifically for windows , but I think you are in Linux , So I have written the code for Linux now. See above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.