top of page
Writer's pictureTolga Koca

Python for Networking— Ping Test

To start python as network engineering, we can start with an easy script which is ping reachability test to the devices. We will create host list as a list variable. And with for loop we will call each of them one by one. So with 1 script we can send many ping request to peer devices. You can use this script to ping any kind of network and system device. First, we import subprocess module first for ping test. import subprocess Than we create function as ping_test with host variable. And we create 2 empty lists. 1 for reachable IP’s and other is not-reachable IP’s. def ping_test (host): reached = [] not_reached = [] Now it’s time to make the for loop and send ping commands to devices. Here we create a loop for host list. Than we run call function under subprocess module. We call ping command for specified host with n times. for ip in host: ping_test = subprocess.call ('ping %s -n 2', % ip) After that we check if ping test successful or not. So we create if statement. If ping_test is 0, than IP is reachable. If ping_test is not equal to 0, IP is no reachable. Also we add this hosts in to lists as reached or not_reached. We created both lists in the beginning of function. if ping_test == 0: reached.append(ip) else: not_reached.append(ip) Than we print the reached and not_reached lists. print("{} is reachable".format(reached)) print("{} not reachable".format(not_reached)) Outside of function we create a new list as hosts. To run the ping_test function, we call it as hosts parameter. hosts = ["192.168.1.1","123.214.2.2","www.google.com",] ping_test (hosts) Finally ping test code is as below.


0 comments

Recent Posts

See All

Comments


bottom of page