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?



# File containing a list of switch IP addresses

# 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"


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


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."

1 Answer 1


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

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

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.