Package ZenUtils :: Module IpUtil
[hide private]
[frames] | no frames]

Source Code for Module ZenUtils.IpUtil

  1  ########################################################################### 
  2  # 
  3  # This program is part of Zenoss Core, an open source monitoring platform. 
  4  # Copyright (C) 2007, Zenoss Inc. 
  5  # 
  6  # This program is free software; you can redistribute it and/or modify it 
  7  # under the terms of the GNU General Public License version 2 as published by 
  8  # the Free Software Foundation. 
  9  # 
 10  # For complete information please visit: http://www.zenoss.com/oss/ 
 11  # 
 12  ########################################################################### 
 13   
 14  __doc__="""Util 
 15   
 16  Utility functions for the Confmon Product 
 17   
 18  """ 
 19   
 20  import types 
 21  import re 
 22  import string 
 23   
 24  from Products.ZenUtils.Exceptions import ZentinelException 
 25   
 26  from twisted.names.client import lookupPointer 
 27   
28 -class IpAddressError(ZentinelException): pass
29 30 31 isip = re.compile("^\d+\.\d+\.\d+\.\d+$").search 32 """return match if this is an ip.""" 33 34
35 -def checkip(ip):
36 """check that an ip is valid""" 37 if ip == '': return 1 38 try: 39 octs = ip.split('.') 40 except: 41 raise IpAddressError( '%s is not a dot delimited address' % ip ) 42 retval = 1 43 #if len(octs) != 4 or int(octs[0]) == 0: 44 if len(octs) != 4: 45 retval = 0 46 else: 47 for o in octs: 48 try: 49 if not (0 <= int(o) <= 255): 50 retval = 0 51 except: 52 retval = 0 53 if not retval: 54 raise IpAddressError( "%s is an invalid address" % ip ) 55 return retval
56 57
58 -def numbip(ip):
59 """convert a string ip to number""" 60 checkip(ip) 61 octs = ip.split('.') 62 octs.reverse() 63 i = 0L 64 for j in range(len(octs)): 65 i += (256l ** j) * int(octs[j]) 66 return i
67 68 _masks = ( 69 0x000000ffL, 70 0x0000ff00L, 71 0x00ff0000L, 72 0xff000000L, 73 ) 74 75
76 -def ipFromIpMask(ipmask):
77 """get just the ip from an ip mask pair like 1.1.1.1/24""" 78 return ipmask.split("/")[0]
79 80
81 -def strip(ip):
82 """convert a number ip to a string""" 83 o = [] 84 for i in range(len(_masks)): 85 t = ip & _masks[i] 86 s = str(t >> (i*8)) 87 o.append(s) 88 o.reverse() 89 return '.'.join(o)
90 91
92 -def hexToBits(hex):
93 """convert hex number (0xff000000 of netbits to numeric netmask (8)""" 94 return maskToBits(hexToMask(hex))
95 96
97 -def hexToMask(hex):
98 '''converts a netmask represented in hex to octets represented in 99 decimal. e.g. "0xffffff00" -> "255.255.255.0"''' 100 101 if hex.find('x') < 0: 102 return "255.255.255.255" 103 104 hex = list(hex.lower().split('x')[1]) 105 octets = [] 106 while len(hex) > 0: 107 snippit = list(hex.pop() + hex.pop()) 108 snippit.reverse() 109 decimal = int(string.join(snippit, ''), 16) 110 octets.append(str(decimal)) 111 112 octets.reverse() 113 return string.join(octets, '.')
114 115
116 -def maskToBits(netmask):
117 """convert string rep of netmask to number of bits""" 118 if type(netmask) == types.StringType and netmask.find('.') > -1: 119 test = 0xffffffffL 120 if netmask[0]=='0': return 0 121 masknumb = numbip(netmask) 122 for i in range(32): 123 if test == masknumb: return 32-i 124 test = test - 2 ** i 125 return None 126 else: 127 return int(netmask)
128 129
130 -def bitsToMaskNumb(netbits):
131 """convert integer number of netbits to string netmask""" 132 masknumb = 0L 133 netbits=int(netbits) 134 for i in range(32-netbits, 32): 135 masknumb += 2L ** i 136 return masknumb
137 138
139 -def bitsToMask(netbits):
140 return strip(bitsToMaskNumb(netbits))
141 142
143 -def getnet(ip, netmask):
144 """get network address of ip as string netmask is in form 255.255.255.0""" 145 checkip(ip) 146 ip = numbip(ip) 147 if 0 < int(netmask) <= 32: 148 netmask = bitsToMaskNumb(netmask) 149 else: 150 checkip(netmask) 151 netmask = numbip(netmask) 152 return ip & netmask
153 154
155 -def getnetstr(ip, netmask):
156 """return network number as string""" 157 return strip(getnet(ip, netmask))
158
159 -def asyncNameLookup(address, uselibcresolver = True):
160 if uselibcresolver: 161 # This is the most reliable way to do a lookup use it 162 from twisted.internet import threads 163 import socket 164 return threads.deferToThread(lambda : socket.gethostbyaddr(address)[0]) 165 else: 166 # There is a problem with this method because it will ignore /etc/hosts 167 address = '.'.join(address.split('.')[::-1]) + '.in-addr.arpa' 168 d = lookupPointer(address, [1,2,4]) 169 def ip(result): 170 return str(result[0][0].payload.name)
171 d.addCallback(ip) 172 return d 173
174 -def asyncIpLookup(name):
175 """ 176 Look up an IP based on the name passed in. We use gethostbyname to make 177 sure that we use /etc/hosts as mentioned above. 178 179 This hasn't been tested. 180 """ 181 from twisted.internet import threads 182 import socket 183 return threads.deferToThread(lambda : socket.gethostbyname(name))
184 185
186 -class InvalidIPRangeError(Exception):
187 """ 188 Attempted to parse an invalid IP range. 189 """
190
191 -def parse_iprange(iprange):
192 """ 193 Turn a string specifying an IP range into a list of IPs. 194 195 @param iprange: The range string, in the format '10.0.0.a-b' 196 @type iprange: str 197 198 >>> parse_iprange('10.0.0.1-5') 199 ['10.0.0.1', '10.0.0.2', '10.0.0.3', '10.0.0.4', '10.0.0.5'] 200 >>> parse_iprange('10.0.0.1') 201 ['10.0.0.1'] 202 >>> try: parse_iprange('10.0.0.1-2-3') 203 ... except InvalidIPRangeError: print "Invalid" 204 Invalid 205 206 """ 207 # Get the relevant octet 208 net, octet = iprange.rsplit('.', 1) 209 split = octet.split('-') 210 if len(split) > 2: # Nothing we can do about this 211 raise InvalidIPRangeError('%s is an invalid IP range.') 212 elif len(split)==1: # A single IP was passed 213 return [iprange] 214 else: 215 start, end = map(int, split) 216 return ['%s.%s' % (net, x) for x in xrange(start, end+1)]
217