Bash – SNMP error reporting to stdout

bashsnmpstderr

Why does net-snmp after "No Such Object available on this agent at this OID" errors exit with 0 and print the error message to STDOUT while other errors are printed to STDERR and have an exit status 1? Compare:

$ /usr/bin/snmpget -Oqv -v2c -cpublic localhost .1.3.6.1.2.1.2.1.0 2> /dev/null
No Such Object available on this agent at this OID
$ echo $?
0

A erroneous community string or IP-Address, however, is handled differently (e.g. "publi" instead of "public"):

$ /usr/bin/snmpget -Oqv -v2c -cpubli localhost .1.3.6.1.2.1.2.1.0 2>&1 > /dev/null
Timeout: No Response from localhost.
$ echo $?
1

This is really irritating as I'm trying to write a function that does some sanity checks to make sure that certain MIBs/OIDs are indeed available on the agent to be queried. I'd like to be able to do something like this (in a bash script):

snmp_sanity_checks() {
  ...
  if ! err=$($snmpcmd); then
    echo "ERROR: $err"
    exit $UNKNOWN
  fi
  ...
}

Does anybody know the reason for this and how I can "fix" it?

Thanks

Best Answer

As another workaround, you can do this:

snmp_sanity_checks() {
  ...
  if ! err=$($snmpcmd); then
    echo "ERROR: $err"
    exit $UNKNOWN
  elif [[ $err == 'No Such Object'* ]]; then
    echo "ERROR: $err"
    exit $UNKNOWN
  fi
  ...
}

Or if you want to handle both situations the same way then this works too:

snmp_sanity_checks() {
  ...
  if ! err=$($snmpcmd) || [[ $err == 'No Such Object'* ]]; then
    echo "ERROR: $err"
    exit $UNKNOWN
  fi
  ...
}