Skip to content

Instantly share code, notes, and snippets.

@spot62
Created November 26, 2024 08:35
Show Gist options
  • Save spot62/abd20ef8bcb9c4353b552d419bf46a24 to your computer and use it in GitHub Desktop.
Save spot62/abd20ef8bcb9c4353b552d419bf46a24 to your computer and use it in GitHub Desktop.
Search port on switches by SNMP FDB table
#!/usr/bin/env bash
COMMUNITY='public'
FDB_OID='.1.3.6.1.2.1.17.7.1.2.2.1.2'
TIMEOUT=5
RETRIES=3
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <MAC> <IP>"
exit 1
fi
# The main code
IFS=':-' read -r -a arr <<< "$1"
mac=$( printf '%d.%d.%d.%d.%d.%d' $((0x${arr[0]})) $((0x${arr[1]})) $((0x${arr[2]})) $((0x${arr[3]})) $((0x${arr[4]})) $((0x${arr[5]})) )
ip=$2
echo "MAC: ${mac}" >&2
echo "IP: ${ip}" >&2
res=$({ snmpbulkwalk -v2c -c ${COMMUNITY} -t ${TIMEOUT} -r ${RETRIES} ${ip} ${FDB_OID} | grep ${mac}; } 2>&1 )
case ${res} in
*INTEGER*)
portnum=$(echo ${res} | sed 's/.*: //')
echo "{\"portnum\": ${portnum}}" >&1
exit 1
;;
*)
res=${res:="Not found"}
echo "{\"msg\": \"${res}\"}" >&1
exit 0
;;
esac
#!/usr/bin/env bash
COMMUNITY='public'
FDB_OID='.1.3.6.1.2.1.17.7.1.2.2.1.2'
TIMEOUT=5
RETRIES=3
# Parse commandline parameters
if [ "$#" -lt 2 ]; then
echo "Usage: $0 <MAC> <host1> <host2> ... <hostN>"
exit 1
else
hosts=( "$@" )
fi
# echo ${hosts[@]}
IFS=':-' read -r -a arr <<< "${hosts[0]}"
mac=$( printf '%d.%d.%d.%d.%d.%d' $((0x${arr[0]})) $((0x${arr[1]})) $((0x${arr[2]})) $((0x${arr[3]})) $((0x${arr[4]})) $((0x${arr[5]})) )
unset hosts[0]
echo "MAC: ${mac}" >&2
echo "Hosts: ${hosts[@]}" >&2
# Make pipe
PIPE=$(mktemp -u)
mkfifo ${PIPE}
# attach it to file descriptor 3
exec {FD}<>${PIPE}
# Function to perform search
function search_mac {
# echo "Searching $1 on $2" >&2
res=$({ snmpbulkwalk -v2c -c ${COMMUNITY} -t ${TIMEOUT} -r ${RETRIES} ${2} ${FDB_OID} | grep ${1}; } 2>&1 )
case ${res} in
*INTEGER*)
portnum=$(echo ${res} | sed 's/.*: //')
echo "{\"host\":\"$2\", \"portnum\": ${portnum}}" >&${FD}
exit 0
;;
*)
res=${res:="Not found"}
echo "{\"host\":\"$2\", \"msg\": \"${res}\"}" >&${FD}
exit 1
;;
esac
}
# Array to hold background process IDs
PIDS=()
# Execute tasks in separate threads
for host in "${hosts[@]}"; do
search_mac $mac $host &
PIDS+=($!)
done
# Wait for all threads to finish
for pid in "${PIDS[@]}"; do
wait $pid
done
# echo "All threads completed." >&2
echo -n "["
sep=''
while read -t 0.1 -u ${FD} line
do
# do something with ${LINE}
echo -n ${sep}${line}
sep=', '
done
echo -n ']'
# unlink the named pipe
# exec ${FD}>&-
# echo ${PIPE}
rm ${PIPE}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment