Mohammad Reza Mousavi
Mohammad Reza Mousavi

Reputation: 1444

Problem when using the ssh-copy-id command in script

I write this for add SSH connection from the list automatically but when I run this script have error! I think this problem relate to read ip from $line variable in script.

My Script:

#!/bin/bash

filename='iplist.txt'
n=1
USER=root
SSHPASS=123456

while read line; do
echo "No. $n : IP = $line"
echo "yes \n" | sshpass -p "$SSHPASS" \
ssh-copy-id -o StrictHostKeyChecking=no $USER@$line \
&& echo "Add successfully!" || echo "FAILED"

echo "########################################"
n=$((n+1))
sleep 2
done < $filename

iplist.txt is a file that's contain my IPs:

172.25.25.1
172.25.25.2 

This is the result of my script:

No. 1 : IP = 172.25.25.1
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed

: Name or service not known: ssh: Could not resolve hostname 172.25.25.1

FAILED
########################################

No. 2 : IP = 172.25.25.2
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed

: Name or service not known: ssh: Could not resolve hostname 172.25.25.2

FAILED
########################################

Upvotes: 0

Views: 1308

Answers (1)

Shaqil Ismail
Shaqil Ismail

Reputation: 1961

  1. check the file endings, if they are CRLF for windows, CR for mac, or LF for linux.
  2. while read -r line; do COMMAND; done The -r option passed to read command prevents backslash escapes from being interpreted. Add IFS= option before read command to prevent leading/trailing whitespace from being trimmed - while IFS= read -r line; do COMMAND_on $line; done

the code above is an example, you may want to use the -r parameter. For IFS you probably do not want to use this, because if there was any whitespace, then IFS would keep this and not remove them.

Upvotes: 1

Related Questions