-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathtcping.py
More file actions
146 lines (130 loc) · 4.96 KB
/
tcping.py
File metadata and controls
146 lines (130 loc) · 4.96 KB
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
#!/usr/bin/env python
# @Author: zhangnq
# @Blog: https://www.szl724.com/
# @Tool: https://tool.nbqykj.cn/software/tcping
import socket,sys
import time
import argparse
from argparse import RawTextHelpFormatter
VERSION = '1.0.1'
ping_cnt = 0
ping_success_cnt = 0
ping_fail_cnt = 0
ping_resp_min = 0
ping_resp_max = 0
ping_resp_avg = 0
ping_resp_total = 0
class MyParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('error: %s\n' % message)
self.print_help()
sys.exit(2)
# get ip from hostname
def host2ip(host):
try:
return socket.gethostbyname(host)
except Exception:
return False
# probing tcp port
def tcp(ip, port, timeout=2):
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk.settimeout(timeout)
try:
t1 = time.time()
sk.connect((ip, port))
t2 = time.time()
sk.close()
return True, int(round((t2-t1)*1000))
except Exception:
sk.close()
return False, timeout*1000
def format_tcp_result(results):
if results[0]:
return "Probing {}:{}/tcp - Port is open - time={}ms".format(ip, port, results[1])
else:
return "Probing {}:{}/tcp - No response - time={}ms".format(ip, port, results[1])
def statistic_tcp_result(results):
global ping_cnt
global ping_success_cnt
global ping_fail_cnt
global ping_resp_min
global ping_resp_max
global ping_resp_avg
global ping_resp_total
# total count
ping_cnt += 1
if results[0]:
# success count
ping_success_cnt += 1
# min ping response time
if ping_resp_min == 0:
ping_resp_min = results[1]
elif results[1] < ping_resp_min:
ping_resp_min = results[1]
# max ping respose time
if results[1] > ping_resp_max:
ping_resp_max = results[1]
# average ping response time
ping_resp_avg = round((ping_resp_total + results[1]) / float(ping_success_cnt), 3)
ping_resp_total += results[1]
else:
# fail count
ping_fail_cnt += 1
return ping_cnt, ping_success_cnt, ping_fail_cnt, ping_resp_min, ping_resp_max, ping_resp_avg
if __name__ == "__main__":
desc = '''--------------------------------------------------------------------------
tcping for linux by zhangnq
Please see http://tool.sijitao.net/software/tcping for more introductions.
--------------------------------------------------------------------------'''
example_text = '''examples:
tcping zhangnq.com
tcping 114.114.114.114 -t -p 53
tcping zhangnq.com -n 10 -p 443 -i 5 -w 1
\n
'''
parser=MyParser(description=desc, formatter_class=RawTextHelpFormatter, epilog=example_text)
parser.add_argument("destination", type=str, help="a DNS name, an IP address")
parser.add_argument("-p", dest="port", type=int, default=80, help="a numeric TCP port, 1-65535. If not specified, defaults to 80.")
parser.add_argument("-t", dest="is_continuously", action='store_true', help="ping continuously until stopped via control-c.")
parser.add_argument("-n", dest="number", type=int, default=4, help="send count pings and then stop, default 4.")
parser.add_argument("-i", dest="interval", type=int, default=1, help="wait seconds between pings, default 1.")
parser.add_argument("-w", dest="wait", type=int, default=2, help="wait seconds for a response, default 2.")
parser.add_argument("-v", "--version", action='version', version=VERSION, help="print version and exit.")
args=parser.parse_args()
ip = host2ip(args.destination)
port = args.port
if not ip:
print("ERROR: Could not find host - %s, aborting" % args.destination)
sys.exit(1)
try:
# continuously
if args.is_continuously:
print("")
print("** Pinging continuously. Press control-c to stop **")
print("")
while True:
results = tcp(ip, port, args.wait)
# print format result
print(format_tcp_result(results))
# start statistic
statistic_tcp_result(results)
time.sleep(args.interval)
else:
print("")
for i in range(args.number):
results = tcp(ip, port, args.wait)
# print format result
print(format_tcp_result(results))
# start statistic
statistic_tcp_result(results)
time.sleep(args.interval)
except KeyboardInterrupt:
print("Control-C")
finally:
format_statistic_results = '''
Ping statistics for {}, port {}:
Probes: send = {}, success = {}, fail = {} ({}% fail)
Approximate trip times:
Minimum = {}ms, Maximum = {}ms, Average = {}ms
'''.format(ip, port, ping_cnt, ping_success_cnt, ping_fail_cnt,round(ping_fail_cnt/float(ping_cnt)*100,2), ping_resp_min, ping_resp_max, ping_resp_avg)
print(format_statistic_results)