lib/snmp/open/command_reader.rb in snmp-open-0.5.0 vs lib/snmp/open/command_reader.rb in snmp-open-0.6.0

- old
+ new

@@ -28,30 +28,43 @@ 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? + raise_capture_errors(err) out end # Generate a CLI command string def cli(command, id = nil, options = {}) command = normalize_command(command) [ command, *options.map { |k, v| "#{k}#{v}" }, + *oid_options(id), *@host_options.map { |k, v| "#{k}#{v}" }, *@command_options.fetch(command, {}).map { |k, v| "#{k}#{v}" }, *id ].join(' ') end private + def raise_capture_errors(err) + case err + when /^Cannot find module \(([^)]+)\)/ + raise UnknownMIBError, "Unknown MIB: #{Regexp.last_match(1)}" + when /^(\S+): Unknown Object Identifier$/ + raise UnknownOIDError, "Unknown OID: #{Regexp.last_match(1)}" + when /^timeout/i + raise CommandTimeoutError, err.chomp + when /./ + raise CommandError, err.chomp + end + end + def merge_options(options = {}) options.each_pair.with_object({}) do |(key, value), opts| if Options::MAP.key?(key) opts[Options::MAP[key]] = (Options::VALUES.fetch(key, {}).fetch(value, value) || next) @@ -61,10 +74,19 @@ raise "Unknown option #{key}" end end end + # if the request OID is all-numeric, force numeric OID in the output + def oid_options(id) + if id =~ /[^0-9.]/ + [] + else + ['-On'] + end + end + def normalize_command(command) case command when Symbol then "snmp#{command}" else command.to_s end @@ -98,7 +120,9 @@ end end # class CommandReader class CommandError < RuntimeError; end class CommandTimeoutError < CommandError; end + class UnknownMIBError < CommandError; end + class UnknownOIDError < CommandError; end end # class Open end # module SNMP