-
Notifications
You must be signed in to change notification settings - Fork 0
/
multiping
executable file
·77 lines (59 loc) · 2.33 KB
/
multiping
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
#!/usr/bin/env ruby
# multiping - ping multiple hosts, give concise feedback on status
# Copyright 2014 by David Lindes. All rights reserved.
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
require 'rubygems'
require 'bundler/setup'
require 'net/ping'
require 'term/ansicolor'
require 'io/console'
require 'resolv'
include Term::ANSIColor
hosts=ARGV
if hosts.empty? then
STDERR.puts "Please provide one or more hosts to ping."
exit 1
end
terminalwidth = IO.console.winsize[1] # TODO: make configurable?
padsize = 2 # TODO: make configurable?
threads = []
resolution = {}
status = {}
pinger = Net::Ping::External.new()
hosts.each do |host|
# stagger pings slightly so we don't flood all outgoing packets all at once (this seems to make things much
# more reliable (even with this small delay), especially for commands with large numbers of hosts specified):
# (without this, I was getting a lot of false negatives. n.b.: this number may yet need tuning.)
sleep(0.008) # TODO: make configurable?
threads << Thread.new {
status[host] = pinger.ping?(host, 10, 0.2, 1)
resolution[host] = Resolv.getaddresses(host).any?
} # host, count, interval, timeout
end
threads.each { |thr| thr.join }
# compute table dimensions:
maxlen = hosts.map {|host| host.length}.max
columns = terminalwidth / (maxlen + padsize)
# print the table:
hosts.each_slice(columns) do |slice|
print slice.map {|host|
str = (status[host] ? host.green : resolution[host] ? host.red : host.magenta)
str + " " * (maxlen - host.length)
}.join(" " * padsize), "\n"
end
# summary:
successes = hosts.count {|host| status[host]}
total = hosts.count
printf "Got to %d hosts out of %d, %0.2f%% success rate.\n", successes, total, 100.0*successes/total
exit successes == total ? 0 : 1