Recently, we talked with you about using Python for network programming. Let me share you an simple example of a Python script, which helps me a lot in my work. Before every course the trainers have to check the lab operation. The next week I will deliver the CCEA (Cisco Contact Center Enterprise Administration) course to seven students, and every student will use his individual lab pod. In the pod there are 13 virtual machines and hardware devices. Before we start the course I have to be sure that all VM are accessible through the network, so I have to connect to every lab pod and ping all the VMs and devices there. Of course, I can do it manually, however, it is time consuming. Let's use Python to automate this and save our time.
The code example is below:
import os
ip_list = ['10.10.1.2','10.10.1.10','10.10.1.20']
for ip in ip_list:
response = os.popen(f"ping {ip}").read()
print(response)
Explanation of the code:
import os - we first need to import the os module to Python to interact with the underlying operating system. The OS module in Python provides functions for creating and removing a directory (folder), fetching its contents, changing and identifying the current directory, pinging, etc.
ip_list = ['10.10.1.2','10.10.1.10','10.10.1.20'] - here we create a list of IP addresses to be pinged. I included just 3 IP addresses for simplicity, however you can add as many IP addresses as you need (you can also add the FQDNs here instead of the IP addresses)
for ip in ip_list: - this command creates a for loop to repeat ping operation several times.
response = os.popen(f"ping {ip}").read() - in this line we create a variable to store the result of ping. The ping itself is provided by os.open() method. So we ping the IP address from the list here and then the output of ping is stored in response variable as string (text)
print (response) - finally we print the result of ping.
The output of this script looks like:
If you don't want such a big output, we can modify our code a bit:
import os
ip_list = ['10.10.1.2','10.10.1.10','10.10.1.20']
for ip in ip_list:
response = os.popen(f"ping {ip}").read()
if "Received = 4" in response:
print(f"UP {ip} Ping Successful")
else:
print(f"DOWN {ip} Ping Unsuccessful")
Instead of printing the whole content of the response variable, we added if-else logic. It will check, if there is 4 successful pings (Received = 4 string) in the response. If yes, then we consider that ping is successful and print just a short message about it. If not, then we print that ping is not successful. However, don't forget about the ARP protocol in your network, when the first ping is unsuccessful because of ARP. In this case to be completely sure that the device is accessible, it it better to run the script twice, or to modify the Python code somehow to provide a correct result with ARP too.
The output of the updated script is below:
Much shorter, right? I hope this example will be useful for you. Cheers!
No comments:
Post a Comment