1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] getting ping using the subprocess function (python3)

Discussão em 'Python' iniciado por Stack, Setembro 5, 2025.

  1. Stack

    Stack Membro Participativo

    (this is just here for anyone who needs it since I'm deleting my account in an hour)

    import subprocess

    for ip in list_of_ip_addresses_or_host_names:
    result = subprocess.run(
    # Command as a list, to avoid shell=True
    ['ping', '-c', '1', ip],
    # Expect textual output, not bytes; let Python .decode() on the fly
    text=True,
    # Shorthand for stdout=PIPE stderr=PIPE etc etc
    capture_output=True,
    # Raise an exception if ping fails (maybe try/except it separately?)
    check=True)
    for line in result.stdout.splitlines():
    # Sample output from my ping:
    # PING hostname.example.com (10.9.8.7): 56 data bytes
    # 64 bytes from 10.130.42.70: icmp_seq=0 ttl=60 time=11.190 ms
    #
    # --- hostname.example.com ping statistics ---
    # 1 packets transmitted, 1 packets received, 0.0% packet loss
    # round-trip min/avg/max/stddev = 11.190/11.190/11.190/0.000 ms
    if "icmp_seq" in line:
    timing = line.split('time=')[-1].split(' ms')[0]
    print(ip, timing)


    (this is just here for anyone who needs it since I'm deleting my account in an hour)

    Continue reading...

Compartilhe esta Página