-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterface-statistics
executable file
·99 lines (76 loc) · 2.46 KB
/
interface-statistics
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
#!/usr/bin/env ruby
#
# Simple script that parses the interface usage statistics
# as returned by 'ip -s link'
#
# This script should be useful for machine statistic collection
# ie: ethernet bytes transmitted and received, etc.
#
# helper assert function
def assert(should_be_true, message)
if !should_be_true
STDERR.puts message
exit(false)
end
end
#
# Parse command options
#
require 'optparse'
options = {}
opt_parser = OptionParser.new do |opts|
opts.banner = "Usage: interface-statistics [options]"
opts.separator ""
options[:format] = :text
opts.on("-f", "--format TYPE", [:text, :hash],
"Specify output format:",
"text: simple text output",
"hash: ruby hash output (useful for use in later ruby scripts)") do |format|
options[:format] = format
end
end
opt_parser.parse!(ARGV)
# get input to parse
#
# try reading from stdin
# otherwise invoke ip -s link directly
if STDIN.tty?
# no pip-ed input...invoke directly
cmd = "ip -s link"
input = `#{cmd}`
assert($?.exitstatus == 0, "Command failed.")
else
input = ARGF.read
end
# split results into lines
lines = input.split("\n")
# sanity check number of lines
assert(lines.length != 0 , "Command output empty")
assert(lines.length % 6 == 0 , "Command output not expected length")
# group lines into block of 6...each interface's results are on 6 lines
interfaces_lines = lines.each_slice(6).to_a
interfaces_hash = {}
# iterate over each interface's set of lines
interfaces_lines.each do |interface_lines|
interface_name = interface_lines[0].split()[1].chomp(":")
# sanity check and get RX
expected_RX_line = " RX: bytes packets errors dropped overrun mcast "
assert(interface_lines[2] == expected_RX_line, "RX line not expected: #{expected_RX_line}")
rx_bytes = interface_lines[3].split()[0].to_i
# sanity check and get TX
expected_TX_line = " TX: bytes packets errors dropped carrier collsns "
assert(interface_lines[4] == expected_TX_line, "TX line not expected: #{expected_TX_line}")
tx_bytes = interface_lines[5].split()[0].to_i
interfaces_hash[interface_name] = { :rx_bytes => rx_bytes, :tx_bytes => tx_bytes };
end
# format output
if options[:format] == :text
# print plain text ouput
puts "interface rx_bytes tx_bytes"
interfaces_hash.each_pair do |name, values|
puts "#{name} #{values[:rx_bytes]} #{values[:tx_bytes]}"
end
else
# print ruby hash string
puts interfaces_hash
end