1
2
3
4
5
6
7
8
9
10
11
12
13
14 ''' pingmonitor
15 creates a queue of hosts to be pinged (jobs),
16 and pings them until they respond, or the
17 maximum number of pings has been sent. After
18 sending out all these pings, we loop in a
19 receive function processing everything we get
20 back'''
21
22 import socket
23 import ip
24 import icmp
25 import os
26 import pprint
27 import time
28 import select
29 import sys
30
32 '''Class representing a single
33 target to be pinged'''
34
36 self._host = host
37 self._rtt = 0
38 self._start = 0
39 self._end = 0
40 self._sent = 0
41
43 self._rtt = 0
44 self._start = 0
45 self._end = 0
46 self._sent = 0
47
53
56
59
62
65
68
70 - def __init__(self, timeout=0.25, tries=3, chunk=25):
71 self._jobQueue = {}
72 self._resultQueue = []
73 self._id = os.getpid()
74 self._timeOut = timeout
75 self._tries = tries
76 self._chunkSize = chunk
77 self._socket = self._createSocket()
78
86
88 self._jobQueue = queueDict
89
96
100
102 timeOut = self._timeOut
103 startTime = time.time()
104 while 1:
105 rd = select.select(
106 [self._socket],
107 [],
108 [],
109 self._timeOut)
110 if rd[0]:
111 (icmppkt, ippkt) = self.recvPacket()
112 source = ippkt.src
113 if queue.has_key(source):
114 jobObj = queue[source]
115 jobObj.end(time.time())
116 jobObj.rtt(
117 jobObj.end() - jobObj.start())
118 self._resultQueue.append(jobObj)
119 del queue[source]
120 timeOut = (startTime + self._timeOut) - time.time()
121 if (not len(queue.keys())
122 or timeOut < 0):
123
124
125
126
127 for item in queue.values():
128 if item.sent() >= self._tries:
129 item.rtt(0.0)
130 self._resultQueue.append(item)
131 del queue[item.host()]
132 break
133
150
152 data = self._socket.recv(4096)
153 if data:
154 ipreply = ip.Packet(data)
155 try:
156 reply = icmp.Packet(ipreply.data)
157 except:
158 return
159 return (reply, ipreply)
160
172
174 '''set jobQueue = chunks
175 remove good pings,
176 leave bad pings until
177 exceed _tries'''
178 for ping in self._jobQueue.values():
179 if ping.sent() >= self._tries:
180 ping.rtt(0.0)
181 del self._jobQueue[ping.host()]
182 self._resultQueue.append(ping)
183
184 for target in chunk:
185 self._jobQueue[target] = PingJob(target)
186
188 chunk = {}
189 targets = self._jobQueue.values()
190 print len(targets), "LEN"
191 print len(targets) % self._chunkSize
192 if len(targets) % self._chunkSize:
193 for _ in range(len(targets) % self._chunkSize):
194 t = targets.pop()
195 chunk[t.host()] = t
196 else:
197 while targets:
198 for _ in range(self._chunkSize):
199 t = targets.pop()
200 chunk[t.host()] = t
201 return chunk
202
203 - def run(self, targets):
218
219
220 if __name__=='__main__':
221
222 if sys.platform == 'win32':
223 time.time = time.clock
224
225 fp = open(sys.argv[1],'r')
226 startTime = time.time()
227 targets = []
228 x = PingMonitor(chunk=2)
229 for target in fp.readlines():
230 targets.append(target[:-1])
231 x.run(targets)
232 x.display()
233 endTime=time.time()
234 print endTime-startTime
235