majorcornwallace

Network Subnet Tool

Apr 19th, 2016
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.00 KB | None | 0 0
  1. import sys
  2. import socket
  3. from socket import inet_aton
  4. from netaddr import *
  5.  
  6. class SubnetTools:
  7.     def __init__(self):
  8.         self.INVALID = -1
  9.    
  10.     def getBitMask(self,netmask):
  11.         b = ''
  12.         for octal in netmask:
  13.             b += bin(int(octal))[2:].zfill(8)
  14.         return str(len(b.rstrip('0')))
  15.        
  16.     def validateIP(self,ip):
  17.         try:
  18.             inet_aton(ip)
  19.         except:
  20.             return False
  21.            
  22.         return True
  23.    
  24.     def createCIDR(self,ipaddr,netmask):
  25.         if(self.validateIP(ipaddr) and self.validateIP(netmask) ):
  26.             ipArray = ipaddr.split('.')
  27.             netArray = netmask.split('.')
  28.  
  29.             # calculate network start
  30.             net_start = [str(int(ipArray[x]) & int(netArray[x])) for x in range(0,4)]
  31.  
  32.             # print CIDR notation
  33.             CIDR_address = '.'.join(net_start) + '/' + self.getBitMask(netArray)
  34.             return (CIDR_address)
  35.         else:
  36.             return(self.INVALID)
  37.            
  38.     def isIPinNetwork(self,ip,cidr):
  39.         set = IPSet([cidr])
  40.         return (ip in set)
  41.        
  42.     def ipListMatchNetwork(self,iplist,network):
  43.         match_list = []
  44.         for ip in iplist:
  45.             if(self.isIPinNetwork(ip,network)):
  46.                 match_list.append(ip)
  47.         return match_list
  48.    
  49.     '''
  50.     convertCIDRtoNetmask() and CIDR2MASK() do the exact same thing -- just two examples
  51.     '''
  52.     def convertCIDRtoNetmask(self,CIDR_address):
  53.         mask = IPNetwork(CIDR_address)
  54.         return mask.netmask
  55.        
  56.     def CIDR2MASK(self,CIDR_address):
  57.         (ip,bits) = CIDR_address.split('/')
  58.         cbits = int(bits)
  59.         mask = []
  60.         if (not isinstance(cbits, int) or cbits < 0 or cbits > 32):
  61.             print ("Error: %s (which is a %s)" % (str(cbits), type(cbits).__name__))
  62.             return None
  63.        
  64.         for t in range(4):
  65.             if cbits > 7:
  66.                 mask.append('255')
  67.             else:
  68.                 dec = 255 - (2**(8 - cbits) - 1)
  69.                 mask.append(str(dec))
  70.  
  71.             cbits -= 8
  72.             if cbits < 0:
  73.                 cbits = 0
  74.  
  75.         return '.'.join(mask)
  76.        
  77. stool = SubnetTools()
  78. ipV4Address = "10.2.10.14"
  79. ipV4Netmask = "255.255.255.248"
  80.  
  81. cidr = stool.createCIDR(ipV4Address,ipV4Netmask)
  82.  
  83. print("IP: %s" % ipV4Address)
  84. print("MASK: %s" % ipV4Netmask)
  85. print("CIDR: %s" % cidr)
  86.  
  87. print("CIDR: %s is MASK: %s" % (cidr,stool.convertCIDRtoNetmask(cidr) ))
  88. print("CIDR: %s is MASK: %s [longhand]" % (cidr,stool.CIDR2MASK(cidr) ))
  89.  
  90. '''
  91. Basic use of isIPinNetwork()
  92.  
  93. '''
  94. FirstIPToCheck = "10.2.10.15"
  95. print("%s is in %s: %s" % (FirstIPToCheck,cidr,stool.isIPinNetwork(FirstIPToCheck,cidr)))
  96.  
  97. SecondIPToCheck = "10.2.10.22"
  98. print("%s is in %s: %s" % (SecondIPToCheck,cidr,stool.isIPinNetwork(SecondIPToCheck,cidr)))
  99.  
  100. '''
  101. Advanced use of isIPinNetwork()using ipListMatchNetwork()
  102.  
  103. Pass an array of IP addresses to test and get back a list of only
  104. the IP addresses that are in the requested network subnet
  105. '''
  106. testIPs = ['10.2.10.15','10.2.10.14','10.2.10.11','10.2.10.22']
  107. subnetIPs = stool.ipListMatchNetwork(testIPs,cidr)
  108. print("Check the following list of IPs: %s" % testIPs)
  109. print("These IPs were in %s:\n\t%s" % (cidr,subnetIPs))
  110.  
  111. # Example of all masks with a dummy ip
  112. #for len in range(32,-1,-1):
  113. #   checkcidr = ("%s/%s") % ("0.0.0.0",len)
  114. #   print ("/%d = %s" % (len, stool.CIDR2MASK(checkcidr)))
Advertisement
Add Comment
Please, Sign In to add comment