1
2
3
4
5
6
7
8
9
10
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
29
30
31 isip = re.compile("^\d+\.\d+\.\d+\.\d+$").search
32 """return match if this is an ip."""
33
34
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
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
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
77 """get just the ip from an ip mask pair like 1.1.1.1/24"""
78 return ipmask.split("/")[0]
79
80
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
93 """convert hex number (0xff000000 of netbits to numeric netmask (8)"""
94 return maskToBits(hexToMask(hex))
95
96
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
128
129
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
141
142
153
154
158
160 if uselibcresolver:
161
162 from twisted.internet import threads
163 import socket
164 return threads.deferToThread(lambda : socket.gethostbyaddr(address)[0])
165 else:
166
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
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
187 """
188 Attempted to parse an invalid IP range.
189 """
190
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
208 net, octet = iprange.rsplit('.', 1)
209 split = octet.split('-')
210 if len(split) > 2:
211 raise InvalidIPRangeError('%s is an invalid IP range.')
212 elif len(split)==1:
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