One of the most import skills for modern network engineers is Python. One of the habits to learning Python was to use it daily as a habit and tie it in directly to my daily needs. What I think gives me those success is when I can make basic tools to make my life easier.
Network engineering is all IP Addresses .Working with the ipaddress module bridges daily tasks with learning python continuously . Something easy is a function to check if whatever is passed in , is an IPv4/v6 address.
#Python3
#Lou D
#Function to return True/False if IPv4/IPv6 passed is valid
import ipaddress
def isIP(address):
try:
valid_ip = ipaddress.ip_address(address)
return True
except:
return False
Something a little practical , a quick script to ping sweep a range a subnet.
#Python3
#Lou D
import ipaddress
import os
#
def pingsweep(prefix):
prefix = (list(ipaddress.ip_network(prefix).hosts()))
#The format function pulls the ip to be used in the function
#format will pull the ip from the address
format(prefix)
for i in prefix:
ip = (format(i))
os.system("ping -c 1 " + ip )1
Simple , easy and it will run some pings to a range of addresses , the return should look something like this
Python3
pingsweep("8.8.8.8/31")
dns.google.
PING 8.8.8.8 (8.8.8.8): 56 data bytes
64 bytes from 8.8.8.8: icmp_seq=0 ttl=118 time=18.459 ms
Anyone coding would tell you there is room for improvement here , there is another method to make DNS queries inside the socket module . You can see a sample output below.
import socket
def revdns(address):
# Address = addr varable
addr = address
domain = socket.getfqdn(addr)
if domain != addr:
print (domain)
return domain
else:
domain = (addr + " no revdns ")
print (domain)
return domain
if __name__ == "__main__":
revdns("8.8.8.8")
I get the most value out of starting small and making more function as I go.
