-1

Having trouble trying to parse data from pinging an IP address. I've been trying to parse data from the ping results and format it like:

IP, TimeToPing (ms)
10.1.2.3, 10

This is where the script is at so far:

import sys
import ipaddress
import subprocess
import os
import re
#Main routine

def main():
    address = sys.argv[1]
    pingthis = ['ping', '-c', '1', address]
    header = "IP, TimeToPing (ms)"
    subprocess.call(pingthis)
    re.search(r'.* time=(.*) ms', os.system('ping -c1'))

if __name__ == "__main__":
    main()
Kusanagi97
  • 23
  • 7

1 Answers1

1

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
baduker
  • 19,152
  • 9
  • 33
  • 56
  • 1
    Thank you for the help and your time. I will need to check out tabulate and stdoutput=subprocess.PIPE and read up on that. – Kusanagi97 May 08 '22 at 20:56