0

I have pieced together a script to login to each switch listed in the file switch.txt, grab the serial number and place it with the IP address into the CSV serials.csv. The problem I am having is that it only does the first device in the list. If I put the credentials in incorrectly, it does go through the rest of the devices, so it seems that when the Cisco device closes the connection, the loop stops.

Does anyone know how I can gracefully end the ssh session so it does not cause the script to stop running?

SCRIPT

#!/bin/bash

# File containing a list of switch IP addresses
SWITCH_LIST="./switch.txt"

# Loop through each IP address in the list
while read IP; do {
  SERIAL=$(sshpass -p globalpass ssh globaluser@$IP "show version" | grep -i "System Serial Number" | awk '{print $NF}')
  echo "$IP,$SERIAL" >> "serials.csv"
  }
done < $SWITCH_LIST

SCRIPT OUTPUT

globaluser@netengmc:~$ ./get_sns.sh
Connection to 10.1.0.254 closed by remote host.

CONTENTS OF SERIALS.CSV

10.1.0.254,FCW3212C2D2

I appreciate any direction to a resolution.

Thank you!

Matthew "When you teach someone what you know, you gain a greater understanding of the subject, which increases your own retention of the knowledge."

2 Answers 2

0

Your ssh command needs the -n option to stop it from reading from stdin. Otherwise, it eats the rest of the input.

2
  • 1
    Also, on newer hardware sho lic udi may be a better command.
    – Ricky
    Commented Jan 16, 2023 at 21:32
  • Thank you Ricky - worked like a charm! =) Commented Jan 16, 2023 at 22:31
0

#!/bin/bash

File containing a list of switch IP addresses

SWITCH_LIST="switch.txt"

Loop through each IP address in the list

while read IP; do { SERIAL=$(sshpass -p password ssh -n -o StrictHostKeyChecking=no username@$IP "show version" | grep -i "System Serial Number" | awk '{print $NF}') echo "$IP,$SERIAL" >> "serials.csv" } done < $SWITCH_LIST

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.