This is a simple and very useful Python script for network administrators to monitor the devices on a network by pinging every IP address on a subnet. On a network that uses DHCP, this script can be used to find out which IP addresses are used and which all are available. This script has been tested on Python version 3.4.3 on Windows platforms. To run this on Linux/Unix platforms just change the parameters for the ping command.
Program Analysis
You need two Python modules - subprocess and ipaddress. The subprocess
module lets you spawn new processes on which you run the ping command. The ipaddress
module is used to define the network and to get the IP addresses that are available on that network.
At first, the program asks the user to input a network address using the CIDR notation (network address/prefix) format. A network is defined using this information and all available IP addresses in that network is obtained as a list.
The IP addresses are put through a loop and the ping command is executed using the popen constructor of subprocess
module. The command output is parsed to check if it contains any of the strings "Destination host unreachable" or "Request timed out" and if found, that IP addresses is marked as offline otherwise it is online.
The ping command in this code limits the number of echo requests to 1 using the -n
switch. If you want to run the program on Linux or Unix platform, replace -n with -c. To make the program run faster the timeout for ping response is set to a low value of 500 milliseconds.
Program Source
# Import modules import subprocess import ipaddress # Prompt the user to input a network address net_addr = input("Enter a network address in CIDR format(ex.192.168.1.0/24): ") # Create the network ip_net = ipaddress.ip_network(net_addr) # Get all hosts on that network all_hosts = list(ip_net.hosts()) # Configure subprocess to hide the console window info = subprocess.STARTUPINFO() info.dwFlags |= subprocess.STARTF_USESHOWWINDOW info.wShowWindow = subprocess.SW_HIDE # For each IP address in the subnet, # run the ping command with subprocess.popen interface for i in range(len(all_hosts)): output = subprocess.Popen(['ping', '-n', '1', '-w', '500', str(all_hosts[i])], stdout=subprocess.PIPE, startupinfo=info).communicate()[0] if "Destination host unreachable" in output.decode('utf-8'): print(str(all_hosts[i]), "is Offline") elif "Request timed out" in output.decode('utf-8'): print(str(all_hosts[i]), "is Offline") else: print(str(all_hosts[i]), "is Online")
Sample Output
A sample output from the program is shown below
Enter a network address in CIDR format(ex.192.168.1.0/24): 10.129.105.0/28
10.129.105.1 is Online
10.129.105.2 is Offline
10.129.105.3 is Offline
10.129.105.4 is Offline
10.129.105.5 is Offline
10.129.105.6 is Offline
10.129.105.7 is Offline
10.129.105.8 is Offline
10.129.105.9 is Offline
10.129.105.10 is Online
10.129.105.11 is Offline
10.129.105.12 is Online
10.129.105.13 is Offline
10.129.105.14 is Offline