#!/usr/bin/env bash
set -euo pipefail
#
# Validate OIDs against a remote SNMP agent.
#
# Usage:
# ./validate-oids.sh <oid-file>
#
# Example:
# ./validate-oids.sh aqnos_oids.txt
#
# The input file is replaced with a filtered version containing
# only OIDs that appear to exist on the remote SNMP agent.
#
if [[ $# -ne 1 ]]; then
echo "Usage: $0 <oid-file>" >&2
exit 1
fi
OID_FILE="$1"
AGENT="192.168.100.100"
COMMUNITY="public"
if [[ ! -f "$OID_FILE" ]]; then
echo "Error: file not found: $OID_FILE" >&2
exit 1
fi
if ! command -v snmpwalk >/dev/null 2>&1; then
echo "Error: snmpwalk is not installed." >&2
exit 1
fi
TMP_FILE="$(mktemp)"
trap 'rm -f "$TMP_FILE"' EXIT
TOTAL=0
KEPT=0
REMOVED=0
ERRORS=0
while IFS= read -r oid || [[ -n "$oid" ]]; do
# Remove CR from Windows-style files.
oid="${oid%$'\r'}"
# Ignore blank lines.
[[ -z "$oid" ]] && continue
((TOTAL += 1))
echo "Checking $oid ..." >&2
#
# Capture both stdout and stderr because Net-SNMP may print
# SNMP errors to either depending on the situation/version.
#
output="$(
snmpwalk \
-v2c \
-c "$COMMUNITY" \
-t 2 \
-r 1 \
"$AGENT" \
"$oid" \
2>&1
)"
status=$?
#
# Typical responses include:
#
# No Such Object available on this agent at this OID
#
# No Such Instance currently exists at this OID
#
# We treat both as "OID does not exist".
#
if grep -Eqi \
'No Such Object|No Such Instance|NoSuchObject|NoSuchInstance' \
<<< "$output"
then
echo " REMOVE: object does not exist" >&2
((REMOVED += 1))
continue
fi
#
# If snmpwalk returned successfully, keep it.
#
if [[ $status -eq 0 ]]; then
echo "$oid" >> "$TMP_FILE"
echo " KEEP" >&2
((KEPT += 1))
continue
fi
#
# Do NOT remove an OID because of timeout, authentication,
# transport or other unexpected errors.
#
echo " WARNING: SNMP error; keeping OID" >&2
echo " $output" >&2
echo "$oid" >> "$TMP_FILE"
((KEPT += 1))
((ERRORS += 1))
done < "$OID_FILE"
#
# Replace original file only after all checks have completed.
#
mv "$TMP_FILE" "$OID_FILE"
trap - EXIT
echo >&2
echo "========================================" >&2
echo "Validation finished" >&2
echo "========================================" >&2
echo "Agent: $AGENT" >&2
echo "File: $OID_FILE" >&2
echo >&2
echo "Checked: $TOTAL" >&2
echo "Kept: $KEPT" >&2
echo "Removed: $REMOVED" >&2
echo "Errors: $ERRORS" >&2