[Python] Writing a Python script to ping a list of IP addresses and return whether the host is...

Discussão em 'Python' iniciado por Stack, Maio 24, 2025.

  1. Stack

    Stack Membro Participativo

    I've written my script to ping a list of IP addresses in a list. However, when I run the script, it just prints all of my IP addresses, but doesn't actually ping them from what I can tell.

    Anyone that could tell me what I'm missing, I'd be most appreciative.

    #!/usr/bin/env python3

    import os

    ip_list = ['8.8.8.8'
    '8.8.4.4'
    '1.1.1.1'
    '4.4.4.4']
    for ip in ip_list:
    response = os.popen(f"ping {ip}").read()
    if "Received = 4" in response:
    print(f"UP {ip} Ping Successful, Host is UP!")
    else:
    print(f"DOWN {ip} Ping Unsuccessful, Host is DOWN.")


    I reworked the code as follows, but it's still not liking something I'm doing. I'm running in a bash shell on macOS.

    #!/usr/bin/env python3

    import subprocess

    ip_list = ['8.8.8.8', '8.8.4.4', '1.1.1.1']
    for ip in ip_list:
    p = subprocess.run(['ping '+ip])
    p.wait()
    if p.poll():
    print (ip+" is down")
    else:
    print (ip+" is up")


    The output I'm getting from that code is here:

    matt$ python3 Python_Ping_Public3.py
    Traceback (most recent call last):
    File "/Users/matt/Desktop/Python_Ping_Public3.py", line 7, in <module>
    p = subprocess.run(['ping '+ip])
    File "/usr/local/Cellar/python@3.9/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 505, in run
    with Popen(*popenargs, **kwargs) as process:
    File "/usr/local/Cellar/python@3.9/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 951, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
    File "/usr/local/Cellar/python@3.9/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 1821, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
    FileNotFoundError: [Errno 2] No such file or directory: 'ping 8.8.8.8'

    Continue reading...

Compartilhe esta Página