Reputation: 207
I'm writting a shell script and I want to automate login into a remote machine using ssh-copy-id, so manually when I print :
ssh-copy-id -i /root/.ssh/id_rsa $2@$4 -p $3 | echo $1
$1 refer to password, $2 refer to username, $3 refer to port, and $4 refer to ip, It is ok with that, the problem is that I have to automate inserting password after :
ssh-copy-id -i /root/.ssh/id_rsa $2@$4 -p $3
I add this "| printf $1", but it does not work it shows "password:" in the screen and still wait for the password .. I hope you understand me and thank you.
Upvotes: 2
Views: 9222
Reputation: 170
2020 / Mac OS X:
Install sshpass (original answer)
brew install hudochenkov/sshpass/sshpass
Run ssh-copy-id
using sshpass
and with the password as an arg
sshpass -p $1 ssh-copy-id -i ~/PATH/TO/KEY $2@$4 -p $3
If you want to turn off strict host checking as well, use the -o
flag, which is passed to the underlying ssh:
sshpass -p hunter2 ssh-copy-id -o StrictHostKeyChecking=no -i ~/PATH/TO/KEY $2@$4 -p $3
I tried the solution by @redneb, and installed setsid
through util-linux by following this answer, but kept receiving a password denied.
I found this strategy to work for uploading my SSH key while setting up multiple raspberry pis in successino. In my script, I also run ssh-keygen -R raspberrypi.local
each time too, to avoid the The ECDSA host key for raspberrypi.local has changed
error.
Upvotes: 1
Reputation: 23850
As @Leon pointed out, you had the pipeline backwards. But even if you do it with the correct order, it will still not work because ssh-copy-id
(and all other programs from openssh
) do not read passwords from their stdin
. The solution is to use the $SSH_ASKPASS
environment variable. You can do that as follows: first, create an auxiliary script, say /var/tmp/ssh-pass.sh
(actually find a better name than that), with the following contents:
#!/bin/sh
echo "$PASS"
Then you can use the following command to accomplish what you've asked for:
PASS="$1" SSH_ASKPASS="/var/tmp/ssh-pass.sh" setsid -w ssh-copy-id -i /root/.ssh/id_rsa "$2"@"$4" -p "$3"
Explanation: we use setsid -w
to disassociate the ssh-copy-id
process from the currently used terminal. That forces ssh-copy-id
to run the executable specified in the $SSH_ASKPASS
in order to obtain the password. We have specified our own script in that variable, so ssh-copy-id
will execute just that. Now the script is supposed to provide the password to ssh-copy-id
by printing it to its stdout. We use the $PASS
variable to the password to the script, so the script just prints that variable.
Upvotes: 3