Home > front end >  Parsing output from ping
Parsing output from ping

Time:05-09

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()

CodePudding user response:

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
  • Related