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

martineau
  • 119,623
  • 25
  • 170
  • 301
Redhwan
  • 927
  • 1
  • 9
  • 24
  • 1
    hmm, how did you get the second row? looks like it's for pinging the same server – rv.kvetch Dec 09 '21 at 04:21
  • 1
    I only ran it twice, you can skip it. – Redhwan Dec 09 '21 at 04:23
  • 1
    If you want to redirect the output of a command to a file I suggest you use the [`subprocess`](https://docs.python.org/3/library/subprocess.html#module-subprocess) module. You will still need to reformat into into CSV format. – martineau Dec 09 '21 at 06:01
  • 2
    Thank you for your suggestion. I have already started using it. – Redhwan Dec 09 '21 at 06:15

1 Answers1

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.

AI - 2821
  • 375
  • 1
  • 7