-
Notifications
You must be signed in to change notification settings - Fork 0
/
pymtr_asyn.py
607 lines (585 loc) · 22.1 KB
/
pymtr_asyn.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
#! /usr/bin/env python3
import sys
import os
import socket
import struct
import time
import logging
import argparse
import asyncio
from collections import namedtuple
from random import random
TARGET = '';
LOGLEVEL = logging.DEBUG;
SIZE = 0;
INTERVAL = 0.2;
TTLMIN = None;
TTLMAX = None;
VERBOSE = None;
PORT = 0;
CYCLE = 0;
REPORT = None;
nEthHeader = 14;
nIpHeader = 20;
nIcmp8Header = 8;
IpObj = namedtuple('IpObj', 'verIhl,dscpEcn,length,ident,flagsOffset,ttl,protocol,checksum,saddr,daddr,options,payload');
IcmpObj = namedtuple('IcmpObj', 'type,code,checksum,ident,seq,payload');
UdpObj = namedtuple('UdpObj', ('sport', 'dport', 'length', 'checksum', 'payload'));
TcpObj = namedtuple('TcpObj', 'sport,dport,seq,ackn,offset,urg,ack,psh,rst,syn,fin,window,checksum,urgp,options,payload');
log = None;
def prepare():
global log;
global LOGLEVEL;
logging.basicConfig();
log = logging.getLogger();
log.setLevel(LOGLEVEL);
socket.setdefaulttimeout(10);
prepare();
def localAddr(sRemote=None):
sock1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);
sRemote = sRemote or '1.1.1.1';
sock1.connect((sRemote, 1));
sAddr = sock1.getsockname()[0]
sock1.close();
return sAddr;
def checksum(bData):
if (len(bData) & 1):
bData += b'\x00';
i = 0;
nSum = 0;
while i < len(bData):
nSum += (bData[i] << 8) + bData[i+1];
i += 2;
nCarry = nSum >> 16;
while nCarry:
nSum = (nSum & 0xffff) + nCarry;
nCarry = (nSum >> 16);
nSum = (~nSum & 0xffff);
return nSum;
def craftIp(ip=None, sDAddr=None, sSAddr=None, nId=None, nFlagsOffset=None, nTtl=None, sProto=None, bData=None):
# Linux will fill in source address, packet ID, IP checksum and total length field.
sDAddr = sDAddr or getattr(ip, 'daddr', None);
assert sDAddr;
bDAddr = socket.inet_aton(sDAddr);
sSAddr = sSAddr or getattr(ip, 'saddr', None);
bSAddr = sSAddr and socket.inet_aton(sSAddr) or b'\x00' * 4;
# (4 << 4) + 5 = 69
nVerIhl = 69;
nId = nId or getattr(ip, 'ident', None) or 0;
# 0b0100000000000000 == 16384, meaning 'don't fragment' only
nFlagsOffset = nFlagsOffset or getattr(ip, 'flagsOffset', None) or 16384;
nTtl = nTtl or getattr(ip, 'ttl', None) or 64;
sProto = sProto;
# socket.getprotobyname('tcp') == 6
nProto = sProto and socket.getprotobyname(sProto) or getattr(ip, 'protocol', 6);
bData = bData or getattr(ip, 'payload', None) or b'';
bHeader = struct.pack('>BBHHHBBH',
nVerIhl, 0, 0,
nId, nFlagsOffset,
nTtl, nProto, 0
);
bHeader += bSAddr + bDAddr;
bIp = bHeader + bData;
#log.debug('crafted ip packet: {}'.format(locals()));
return bIp;
def craftIcmp(icmp=None, bData=b'', nSize=0, nId=0, nSeq=0):
nType = 8;
nCode = 0;
nCheck = 0;
nId = nId or getattr(icmp, 'ident', None) or os.getpid();
nSeq = nSeq or getattr(icmp, 'seq', None) or 1;
bData = bData or getattr(icmp, 'payload', None) or (nSize and nSize * b'\x00') or b'';
bHeader = struct.pack('>BBHHH', nType, nCode, nCheck, nId, nSeq);
bIcmp = bHeader + bData;
nCheck = checksum(bIcmp);
bHeader = struct.pack('>BBHHH', nType, nCode, nCheck, nId, nSeq);
bIcmp = bHeader + bData;
return bIcmp;
def craftUdp(udp=None, sSAddr=None, sDAddr=None, nSPort=None, nDPort=None, bData=None, nSize=None):
nSPort = nSPort or getattr(udp, 'sport', 0);
nDPort = nDPort or getattr(udp, 'dport', 0);
bData = bData or getattr(udp, 'payload', b'') or (nSize and nSize * b'\x00') or b'';
nLength = len(bData) + 8;
nCheck = 0;
bHeader = struct.pack('>HHHH', nSPort, nDPort, nLength, nCheck);
bUdp = bHeader + bData;
if (sSAddr and sDAddr):
bPseudo = socket.inet_aton(sSAddr) + socket.inet_aton(sDAddr) + struct.pack('>BBH', 0, 17, len(bUdp));
nCheck = checksum(bPseudo + bUdp);
bHeader = struct.pack('>HHHH', nSPort, nDPort, nLength, nCheck);
bUdp = bHeader + bData;
return bUdp;
def craftTcp(tcp=None, sSAddr=None, sDAddr=None, nSPort=0, nDPort=0, nSeq=0, nAckn=0, urg=0, ack=0, psh=0, rst=0, syn=0, fin=0, nWindow=0, nUrgp=0, bOptions=None, bData=None, nSize=0):
nSPort = nSPort or getattr(tcp, 'sport', 0);
nDPort = nDPort or getattr(tcp, 'dport', 0);
nSeq = nSeq or getattr(tcp, 'seq', 0) or int(random() * 10000);
nAckn = nAckn or getattr(tcp, 'ackn', 0);
bOptions = bOptions or getattr(tcp, 'options', b'');
bOptions += b'\x00' * (-len(bOptions) % 4)
nOffset = 5 + len(bOptions) // 4;
assert nOffset >> 4 == 0;
urg = bool(urg or getattr(tcp, 'urg', 0));
ack = bool(ack or getattr(tcp, 'ack', 0));
psh = bool(psh or getattr(tcp, 'psh', 0));
rst = bool(rst or getattr(tcp, 'rst', 0));
syn = bool(syn or getattr(tcp, 'syn', 0));
fin = bool(fin or getattr(tcp, 'fin', 0));
nORF = (nOffset << 12) + (urg << 5) + (ack << 4) + (psh << 3) + (rst << 2) + (syn << 1) + fin;
nWindow = nWindow or getattr(tcp, 'window', 29200);
nCheck = 0;
nUrgp = nUrgp or getattr(tcp, 'urgp', 0);
bData = bData or getattr(tcp, 'payload', b'') or (nSize and nSize * b'\x00') or b'';
bHeader = struct.pack('>HHLLHHHH', nSPort, nDPort, nSeq, nAckn, nORF, nWindow, nCheck, nUrgp);
bTcp = bHeader + bOptions + bData;
bPseudo = socket.inet_aton(sSAddr) + socket.inet_aton(sDAddr) + struct.pack('>BBH', 0, 6, len(bTcp));
nCheck = checksum(bPseudo + bTcp);
bHeader = struct.pack('>HHLLHHHH', nSPort, nDPort, nSeq, nAckn, nORF, nWindow, nCheck, nUrgp);
bTcp = bHeader + bOptions + bData;
return bTcp;
def parseIp(bIn):
assert len(bIn) >= 20;
global IpObj;
(
verIhl, dscpEcn, length,
ident, flagsOffset,
ttl, protocol, checksum
) = struct.unpack('>BBHHHBBH', bIn[:12]);
saddr = socket.inet_ntoa(bIn[12:16]);
daddr = socket.inet_ntoa(bIn[16:20]);
nVersion = verIhl >> 4;
if (not nVersion == 4):
return False;
nHeaderLength = verIhl & 0xf;
nOffset = nHeaderLength * 4;
options = bIn[20:nOffset];
payload = bIn[nOffset:]
ip = IpObj(verIhl, dscpEcn, length, ident, flagsOffset, ttl, protocol, checksum, saddr, daddr, options, payload);
return ip;
def parseIcmp(bIn):
global IcmpObj;
#nType, nCode, nCheck, nId, nSeq = struct.unpack('>BBHHH', bIn[:8]);
aIcmp = struct.unpack('>BBHHH', bIn[:8]);
bData = bIn[8:];
#icmp = IcmpObj(nType, nCode, nCheck, nId, nSeq, bData);
icmp = IcmpObj(*aIcmp, bData);
return icmp;
def parseUdp(bIn):
global UdpObj;
aUdp = struct.unpack('>HHHH', bIn[:8]);
bData = bIn[8:]
udp = UdpObj(*aUdp, bData);
return udp;
def parseTcp(bIn):
global TcpObj;
sport, dport, seq, ackn, nORF, window, checksum, urgp = struct.unpack('>HHLLHHHH', bIn[:20])
offset = (nORF >> 12);
nOffset = offset * 4;
urg = (nORF >> 5) & 1;
ack = (nORF >> 4) & 1;
psh = (nORF >> 3) & 1;
rst = (nORF >> 2) & 1;
syn = (nORF >> 1) & 1;
fin = nORF & 1;
bOptions = bIn[20: nOffset];
bData = bIn[nOffset:];
tcp = TcpObj(sport, dport, seq, ackn, offset, urg, ack, psh, rst, syn, fin, window, checksum, urgp, bOptions, bData);
return tcp;
class Hop():
@property
def nRecv(self):
return len(self.aRtts);
@property
def nLast(self):
if (self.aRtts):
return self.aRtts[-1];
else:
return 0;
@property
def nMin(self):
if (self.aRtts):
return min(self.aRtts);
else:
return 0;
@property
def nMax(self):
if (self.aRtts):
return max(self.aRtts);
else:
return 0;
@property
def nAvg(self):
if (self.aRtts):
return sum(self.aRtts) / self.nRecv;
else:
return 0;
@property
def nMdev(self):
if (self.aRtts):
nSquareSum = sum(map(lambda x:x*x, self.aRtts))
nMdev = (nSquareSum / self.nRecv - self.nAvg ** 2) ** 0.5;
return nMdev
else:
return 0;
@property
def nLossRate(self):
return (1 - self.nRecv / self.nSent) * 100;
def __init__(self, nHop, sAddr=None, aRtts=None):
self.nHop = int(nHop);
self.sAddr = sAddr or '';
self.aAddrs = [];
if (self.sAddr):
self.aAddrs.append(self.sAddr);
self.aRtts = aRtts or [];
self.mIdMap = {};
self.mSPortMap = {};
self.mIcmpSeqMap = {};
self.nSent = 0;
#self.nRecv
#self.nMin
#self.nMax
#self.nAvg
#sefl.nMdev
#self.nLossRate
def addHost(self, sAddr):
assert sAddr;
if (not self.sAddr): self.sAddr = sAddr;
if (not sAddr in self.aAddrs): self.aAddrs.append(sAddr);
def addRtt(self, nRtt):
self.aRtts.append(nRtt);
class Mtr():
def __init__(self, sTarget, nTtlMin=None, nTtlMax=None, nInterval=None, isVerbose=None, nCycle=0, isReport=None, loop=None):
global TTLMIN, TTLMAX, INTERVAL, VERBOSE, CYCLE, REPORT;
self.loop = loop or asyncio.get_event_loop();
self.sTarget = sTarget;
self.sAddr = socket.gethostbyname(sTarget);
self.sHost = localAddr(self.sAddr);
self.nTtlMin = int(nTtlMin or TTLMIN or 1);
self.nTtlMax = int(nTtlMax or TTLMAX or 30);
assert self.nTtlMin < self.nTtlMax;
self.nInterval = float(nInterval or INTERVAL or 0.2);
self.isVerbose = isVerbose if isVerbose is not None else VERBOSE;
self.nCycle = int(nCycle or CYCLE or 0);
self.isReport = isReport if isReport is not None else REPORT;
self.aHops = [];
self.sProtocol = None;
self.nFirstId = os.getpid() + (int(time.time()) & 0xfff) or 1; # first IP identification
self.sendSock = None;
self.recvSock = None;
self.goalSock = None;
self.nTtlCursor = 0;
self.topHop = 0;
self.topAddr = None;
self.isRunning = False;
self.isSending = False;
self.nLines = 0; # lines printed
self.aOutput = [];
self.mCache = {};
def findAndPurge(self, index, sAttr):
# search IP packet and auxiliary information within some most current hops, older data shall be purged
# hops range from 1 to len(aHops), differing from index of aHops by 1;
nEnd = self.nTtlCursor - 1;
nStart = nEnd - len(self.aHops) + 1
nBound = max(nEnd - 9, nStart);
nCursor = nStart;
while nCursor <= nEnd:
hop = self.aHops[nCursor];
if (hop):
if (nCursor < nBound):
setattr(hop, sAttr, {});
else:
mInfo = getattr(hop, sAttr).get(index);
if (mInfo):
return mInfo;
nCursor += 1;
return False;
def reset(self):
self.aHops = [];
self.topHop = 0;
self.topAddr = None;
self.isRunning = False;
self.isSending = False;
if (self.sendSock):
self.sendSock.close();
self.sendSock = None;
if (self.recvSock):
self.loop.remove_reader(self.recvSock);
self.recvSock.close();
self.recvSock = None;
if (self.goalSock):
self.loop.remove_reader(self.goalSock);
self.goalSock.close();
self.goalSock = None;
self.loop.stop();
for task in asyncio.Task.all_tasks():
task.close();
self.loop.close();
def startSend(self):
raise NotImplementedError;
def updateOneLine(self, nHop, isSent=False):
for i in range(len(self.aOutput), nHop):
self.aOutput.append('{:>2}. ???'.format(i + 1));
hop = self.aHops[nHop - 1];
if (isSent):
aArgs = self.mCache.get(nHop)
if (not aArgs):
aArgs = [0,] * 10;
aArgs[1] = hop.sAddr;
aArgs[0] = nHop;
aArgs[2] = hop.nLossRate;
aArgs[3] = hop.nSent;
else:
sAddr = hop.sAddr;
if (len(hop.aAddrs) > 1):
sAddr += ' and {} more'.format(len(hop.aAddrs) - 1);
aArgs = [
nHop, sAddr, hop.nLossRate, hop.nSent, hop.nRecv,
hop.nLast, hop.nAvg, hop.nMin, hop.nMax, hop.nMdev
];
self.mCache[nHop] = aArgs;
sLine = (
'{:>2}. {:<30} {:>5.1f}% {:>5} {:>5}' +
' {:>6.1f} {:>6.1f} {:>6.1f} {:>6.1f} {:>6.1f}'
).format(*aArgs);
self.aOutput[nHop - 1] = sLine;
def updateDisplay(self, nHop, isSent=False):
if (self.nLines):
sys.stderr.write('\033[{}F\033[0J'.format(self.nLines));
if (nHop > 0):
self.updateOneLine(nHop, isSent);
else:
for i in range(1, len(self.aHops)):
self.updateOneLine(i, isSent);
sOutput = '\n'.join(self.aOutput) + '\n';
sys.stderr.write(sOutput);
self.nLines = len(self.aOutput);
def handleReply(self, bIp, sHopAddr):
nRecvTime = time.monotonic() * 1000;
ip = parseIp(bIp);
assert sHopAddr == ip.saddr;
icmp = parseIcmp(ip.payload);
if not (icmp.type == 11 and icmp.code == 0):
return False;
oriIp = parseIp(icmp.payload);
mSent = self.findAndPurge(oriIp.ident, 'mIdMap');
if (mSent):
sentIp = mSent['ip'];
nSentTime = mSent['nSent'];
nRtt = nRecvTime- nSentTime;
nHop = sentIp.ttl;
hop = self.aHops[nHop-1];
assert hop;
hop.addHost(sHopAddr);
hop.addRtt(nRtt);
if (not self.isReport):
self.loop.call_soon(self.updateDisplay, nHop);
return True;
else:
return False
def startReceive(self):
global parseIp;
self.recvSock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP);
self.recvSock.settimeout(0);
def readOne():
if (self.isRunning):
bIp, aHopAddr = self.recvSock.recvfrom(4096);
sHopAddr = aHopAddr[0];
self.handleReply(bIp, sHopAddr);
else:
self.remove_reader(self.recvSock);
self.recvSock.close();
self.recvSock = None;
self.loop.add_reader(self.recvSock, readOne);
def startGoalCheck(self):
raise NotImplementedError;
def output(self):
sys.stderr.write('\n');
for hop in self.aHops:
if (not hop):
continue;
if (hop.sAddr):
sAddrs = ', '.join(hop.aAddrs);
#sRtts = ', '.join(str(round(x, 3)) for x in hop.aRtts);
sOutput = '\n'.join([
'hop {} from {}:',
' {} packets transmitted, {} received, {:.3f}% packet loss',
' rtt min/avg/max/mdev = {:.3f}/{:.3f}/{:.3f}/{:.3f} ms',
''
]).format(
hop.nHop, sAddrs,
hop.nSent, hop.nRecv, hop.nLossRate,
hop.nMin, hop.nAvg, hop.nMax, hop.nMdev
);
sys.stderr.write(sOutput);
else:
sys.stderr.write('hop {}: no packet received\n'.format(hop.nHop));
sys.stderr.write('\n');
def run(self):
sys.stdout.write('mtr to {} ({}), {} hops min, {} hops max, {} bytes payload, {} seconds interval, {} cycles\n'
.format(self.sTarget, self.sAddr, self.nTtlMin, self.nTtlMax, self.nSize, self.nInterval, self.nCycle)
);
sys.stderr.write('{0:46}Packets{0:30}Pings\n'.format(''));
sys.stderr.write(' Host {:28} Loss% Snt Rcv Last Avg Best Wrst StDev\n'.format(''));
self.isRunning = True;
self.startReceive();
self.startGoalCheck();
self.startSend();
try:
self.loop.run_forever();
except KeyboardInterrupt as e:
self.loop.stop();
print();
finally:
self.isSending = False;
self.isRunning = False;
if (self.isReport):
self.updateDisplay(0);
if (self.isVerbose):
self.output();
self.reset();
class IcmpMtr(Mtr):
def __init__(self, sTarget, nTtlMin=None, nTtlMax=None, nSize=None):
super().__init__(sTarget, nTtlMin, nTtlMax)
self.sProtocol = 'icmp';
self.nSize = nSize or SIZE or 32;
self.nIcmpId = int(time.time()) & 0xffff or 1;
def startSend(self):
global IpObj
self.sendSock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW);
self.isSending = True;
nIpId = self.nFirstId;
nIcmpSeq = 1;
nTtl = self.nTtlMin;
nCycle = 1;
if (not self.aHops):
self.aHops = [None] * (nTtl - 1);
def sendOne():
nonlocal nIpId, nIcmpSeq, nTtl, nCycle;
self.nTtlCursor = nTtl;
hop = self.aHops[nTtl-1:nTtl];
hop = hop and hop[0];
if (not hop):
hop = Hop(nTtl);
self.aHops.append(hop);
assert len(self.aHops) == nTtl;
bIcmp = craftIcmp(nSize=self.nSize, nId=self.nIcmpId, nSeq=nIcmpSeq);
bIp = craftIp(sDAddr=self.sAddr, nId=nIpId, nTtl=nTtl, sProto='icmp', bData=bIcmp);
ip = parseIp(bIp);
self.sendSock.sendto(bIp, (self.sAddr, 0));
nSentTime = time.monotonic() * 1000;
hop.mIdMap[nIpId] = {
'ip': ip,
'nSent': nSentTime
};
hop.mIcmpSeqMap[nIcmpSeq] = {
'ip': ip,
'nSent': nSentTime
};
hop.nSent += 1;
if (not self.isReport):
self.loop.call_soon(self.updateDisplay, nTtl, True);
if (
self.isSending and self.isRunning and
(not self.nCycle or nCycle <= self.nCycle)
):
nIcmpSeq = (nIcmpSeq + 1) & 0xffff or 1;
nIpId = (nIpId + 1) & 0xffff or 1;
if (nTtl < self.nTtlMax):
nTtl = nTtl + 1
else:
nTtl = self.nTtlMin;
nCycle += 1;
self.loop.call_later(self.nInterval, sendOne)
else:
self.isSending = False;
self.loop.stop();
self.sendSock.close();
self.sendSock = None;
sendOne();
def startGoalCheck(self):
self.goalSock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP);
self.goalSock.settimeout(0);
def checkOne():
if (self.isRunning):
nRecvTime = time.monotonic() * 1000;
bIp, aRemote = self.goalSock.recvfrom(4096);
sRemote = aRemote[0];
if (sRemote == self.sAddr):
ip = parseIp(bIp);
icmp = parseIcmp(ip.payload);
if (icmp.type == 0 and icmp.code == 0 and icmp.ident == self.nIcmpId):
mSent = self.findAndPurge(icmp.seq, 'mIcmpSeqMap');
if (mSent):
sentIp = mSent['ip'];
nSentTime = mSent['nSent'];
nRtt = nRecvTime - nSentTime;
nHop = sentIp.ttl;
hop = self.aHops[nHop-1];
hop.addHost(sRemote);
hop.addRtt(nRtt);
if (nHop < self.nTtlMax):
self.nTtlMax = nHop;
if (not self.isReport):
self.loop.call_soon(self.updateDisplay, nHop);
else:
self.remove_reader(self.goalSock);
self.goalSock.close();
self.goalSock = None;
self.loop.add_reader(self.goalSock, checkOne);
def parseArg():
global LOGLEVEL, TARGET, SIZE, INTERVAL, TTLMIN, TTLMAX, PORT, VERBOSE, CYCLE, REPORT;
global log
parser = argparse.ArgumentParser(description='mtr in python3 using asynio, need superuser privilege, only ICMP implemented; use ctrl+c to terminate; ');
parser.add_argument('target',
help='target address'
);
group1 = parser.add_mutually_exclusive_group();
group1.add_argument('-s', '--size',
help='set the size of data used as probe'
);
parser.add_argument('-i', '--interval',
help='set interval between each packet sent'
);
parser.add_argument('-f', '--firsttl',
help='set the initial time to live IP header field'
);
parser.add_argument('-m', '--maxttl',
help='set the maximum time to live IP header field'
);
parser.add_argument('-v', '--verbose',
action='store_true',
help='show debug output'
);
parser.add_argument('-c', '--cycle',
help='set the count to cycle; defaluts to 0 meaning cycling until terminated by user;'
);
parser.add_argument('-r', '--report',
action='store_true',
help='report mode, supress output while running and display the output when terminated instead; could be combined with -c'
);
args = parser.parse_args();
if (args.verbose):
LOGLEVEL = logging.DEBUG;
else:
LOGLEVEL = logging.INFO;
log.setLevel(LOGLEVEL);
VERBOSE = bool(args.verbose);
TARGET = args.target;
SIZE = int(args.size or SIZE or 0);
INTERVAL = float(args.interval or INTERVAL or 0);
TTLMIN = int(args.firsttl or TTLMIN or 0);
TTLMAX = int(args.maxttl or TTLMAX or 0);
CYCLE = int(args.cycle or CYCLE or 0);
REPORT = args.report;
log.debug('passed command line arguments: {}'.format(
{key: value for (key, value) in vars(args).items() if value is not None}
));
return args;
def main():
global TARGET;
if (sys.platform == 'win32'):
raise NotImplementedError('modifying IP header of raw socket is not supported on Windows!');
parseArg();
mtr = IcmpMtr(TARGET);
mtr.run();
if __name__ == '__main__':
main();