Class: SNMP::Open::CommandReader

Inherits:
Object
  • Object
show all
Defined in:
lib/snmp/open/command_reader.rb

Overview

Open3-based data source that executes an snmp* command and captures the output

Constant Summary collapse

OPTIONS =

see snmpcmd(1) for explanation of options

{
  version: '-v',
  auth_password: '-A',
  auth_protocol: '-a',
  community: '-c',
  context: '-n',
  no_check_increasing: {
    'snmpbulkwalk' => '-Cc',
    'snmpwalk' => '-Cc'
  },
  numeric: '-On', # needed by parser, should always be enabled
  priv_password: '-X', # not recommended, see snmp.conf(5)
  priv_protocol: '-x',
  sec_level: '-l',
  sec_user: '-u',
  retries: '-r',
  timeout: '-t',
  host: nil
}.freeze
OPTION_VALUES =
{
  no_check_increasing: {
    true => ''
  }.freeze
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ CommandReader

options accepts options dealing with making connections to the host, including all of the options listed in the OPTIONS constant hash. Other options can be given as strings (or any object with a suitable to_s method), e.g., these are equivalent:

SNMP::Open.new(host: hostname, timeout: 3, '-m' => miblist)
SNMP::Open.new(hostname => nil, '-t' => '3', '-m' => miblist)


43
44
45
46
47
48
49
# File 'lib/snmp/open/command_reader.rb', line 43

def initialize(options)
  @env = options.delete(:env)
  host = options.delete(:host) ||
         (raise ArgumentError, 'Host expected but not given')
  opts = merge_options(options).merge('-On' => nil, host => nil)
  @command_options, @host_options = partition_options(opts)
end

Instance Method Details

#capture(cmd, oid, options = {}) ⇒ Object



51
52
53
54
55
56
57
58
59
60
# File 'lib/snmp/open/command_reader.rb', line 51

def capture(cmd, oid, options = {})
  out, err = if @env
               Open3.capture3(@env, cli(cmd, oid, options))
             else
               Open3.capture3(cli(cmd, oid, options))
             end
  raise CommandTimeoutError, err.chomp if err =~ /^timeout/i
  raise CommandError, err.chomp unless err.empty?
  out
end

#cli(command, id = nil, options = {}) ⇒ Object

Generate a CLI command string



63
64
65
66
67
68
69
70
71
72
73
# File 'lib/snmp/open/command_reader.rb', line 63

def cli(command, id = nil, options = {})
  command = normalize_command(command)

  [
    command,
    *options.map { |k, v| "#{k}#{v}" },
    *@host_options.map { |k, v| "#{k}#{v}" },
    *@command_options.fetch(command, {}).map { |k, v| "#{k}#{v}" },
    *id
  ].join(' ')
end