[Python Patterns] Just a Ping session

This one Pings a host IP and brings back some DNS using the local ping command. Should work on OSX, Linux, and Windows.

This one Pings a host IP and brings back some DNS using the local ping command. Should work on OSX, Linux, and Windows.

from platform import system as system_name
import socket
import subprocess

def ping(host):
    """ Just a ping session """
    host_dict = {"DNS": "", "IP": "", "PING": ""}
    # Verify what OS we are on.
    # Windows ping.exe takes a -c arg, POSIX systems take -n
    os_check = "-n" if system_name().lower() == "windows" else "-c"
    proc = subprocess.Popen(['ping', os_check, '3', host], stdout=subprocess.PIPE)
    stdout, stderr = proc.communicate()
    print(stdout)
    if stderr:
        logger.warning(stderr)
        print("Something's up with {0} it threw this: {1}".format(host, stderr))
    if proc.returncode == 0:
        host_dict["PING"] = "UP"
    else:
        host_dict["PING"] = "DOWN"
    # Try to get hostname from DNS
    try:
        name = socket.gethostbyaddr(host)
    except socket.herror:
        logger.warning(socket.herror)
        print("DNS failed on {0}:  {1}".format(host, socket.herror))
        name = ["None", "None", "None"]
    host_dict["DNS"] = name[0]
    host_dict["IP"] = host
    print(host_dict)
    return host_dict

Output:

Example of two servers named link and zelda

>>> ping("192.168.1.2")
b'PING 192.168.1.2 (192.168.1.2): 56 data bytes\nRequest timeout for icmp_seq 0\nRequest timeout for icmp_seq 1\n\n--- 192.168.1.2 ping statistics ---\n3 packets transmitted, 0 packets received, 100.0% packet loss\n'
{'DNS': 'link.example.com', 'IP': '192.168.1.2', 'PING': 'DOWN'}
{'DNS': 'link.example.com', 'IP': '192.168.1.2', 'PING': 'DOWN'}
>>> 
>>> ping("192.168.1.3")
b'PING 192.168.1.3 (192.168.1.3): 56 data bytes\n64 bytes from 192.168.1.3: icmp_seq=0 ttl=64 time=17.635 ms\n64 bytes from 192.168.1.3: icmp_seq=1 ttl=64 time=6.689 ms\n64 bytes from 192.168.1.3: icmp_seq=2 ttl=64 time=5.257 ms\n\n--- 192.168.1.3 ping statistics ---\n3 packets transmitted, 3 packets received, 0.0% packet loss\nround-trip min/avg/max/stddev = 5.257/9.860/17.635/5.529 ms\n'
{'DNS': 'zelda.example.com', 'IP': '192.168.1.3', 'PING': 'UP'}
{'DNS': 'zelda.example.com', 'IP': '192.168.1.3', 'PING': 'UP'}
>>> 

My blog posts tagged with "Python Patterns" are designed to be a quick look reference for some Python code snippets I use a lot.  They are written to be a quick starting point for future projects so I do not need to type as much.