summaryrefslogtreecommitdiffstats
path: root/ping-ssh
blob: 711d8b6a6a06ef428bc54fe1762064996a5b309a (plain)
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
#!/usr/bin/python

from timeit import default_timer as timer
import statistics
import subprocess
import sys

if len(sys.argv) <= 3:
    print("usage: ping-ssh <host> <repeat count> <string>")
    sys.exit(1)

host = sys.argv[1]
repeat = int(sys.argv[2])
ping_string = sys.argv[3]

def ping(stdin, stdout):
    ping_bytes = (ping_string+"\n").encode()
    stdin.write(ping_bytes)
    result = stdout.read(len(ping_bytes))
    assert result == ping_bytes

proc = subprocess.Popen(['ssh', host, 'cat'],
        bufsize=0,
        stdout=subprocess.PIPE, stdin=subprocess.PIPE)

# ping once to ensure the "connection" is ready. Without this the first ping
# would be much slower than all others due to ssh/cat starting up
ping(proc.stdin, proc.stdout)

times = []

for i in range(repeat):
    start = timer()
    ping(proc.stdin, proc.stdout)
    end = timer()
    time = end - start
    times.append(time)
    print("{:.5f}ms".format(time * 1000))
    sys.stdout.flush()

print("")
print("mean:   {:.5f}ms".format(statistics.mean(times) * 1000))
print("median: {:.5f}ms".format(statistics.median(times) * 1000))
print("min:    {:.5f}ms".format(min(times) * 1000))
print("max:    {:.5f}ms".format(max(times) * 1000))

proc.stdin.close()
proc.wait()