Auto answer ssh-copy-id in shell script - bash

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.

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.

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.

Related

sshpass want to use parameter of sftp

Hi i created following script to initialize my storage box to use rsync without password later. Last year it works if i remember correct...
cat .ssh/id_rsa.pub >> .ssh/storagebox_authorized_keys
echo -e "mkdir .ssh \n chmod 700 .ssh \n put $.ssh/storagebox_authorized_keys" \
".ssh/authorized_keys \n chmod 600 .ssh/authorized_keys" | sshpass -p ${storage_password} \
sftp -P ${storage_port} -i .ssh/id_rsa ${storage_user}#${storage_address}
today I get following error:
sshpass: invalid option -- 'i'
but the parameter -i belongs to sftp and not sshpass - is there an possibility to parse the parameters in the correct way?
edit: i switched the position of
-i .ssh/id_rsa ${storage_user}#${storage_address}
and get this error
sshpass: Failed to run command: No such file or directory
edit: it seems like an sftp problem...
after discussion, updating answer to properly support automation
step 1:
create an sftp "batch file" e.g: ~/.ssh/storage-box_setup.sftp
mkdir .ssh
chmod 700 .ssh
put /path/to/authorized_keys_file ".ssh/authorized_keys
chmod 600 .ssh/authorized_keys
/path/to/authorized_keys_file is a file containing public keys of ONLY the keys that should have access to your storage box (.ssh/storagebox_authorized_keys)
step 2:
update automation script command to
sshpass -p <password> -- sftp -P <port> -b ~/.ssh/storage-box_setup.sftp user#host
the -b flag was the answer you needed.
refer: man sftp
-b batchfile
Batch mode reads a series of commands from an input batchfile instead of stdin. Since it lacks user interaction it should be used in conjunction with non-interactive authentication.
--
sshpass -p ${storage_password} -- \
sftp -P ${storage_port} -i .ssh/id_rsa \
${storage_user}#${storage_address}
the -- before sftp is a way to tell sshpass (and most other programs) to stop parsing arguments.
everything after -- is assumed as the last argument, which in the case of sshpass is the command to be executed ssh -i ~/.id_rsa ...
in case you're wondering switching the position of -i tells sshpass to execute -i as a program and hence fails with command not found

script to connect to a "list.txt" of servers

I am trying to find a way to connect to a list of servers written in a simple textfile to run one command and write the output to a file...
The small problem is, I have to login with a password... but it would not a problem to paste the password into the script.
the full command would be:
ssh "server_from_list.txt uptime | awk -F, '{sub(".*up ",x,$1);print $1}' >> /home/kauk2/uptime.out
lets assume the password is: abcd1234
Any suggestions??? I am not fit in scripting, sorry...
Many thanks to you all in advance...
regards,
Joerg
Ideally you should set up password-less login, but failing that you can use sshpass. First, get a single command working by trying the following:
export SSHPASS=abcd1234
Then you can try:
sshpass -e ssh user#server1 'uname -a'
When you get that debugged and working, you can use GNU Parallel to run the command on all servers in a file called list.txt
user#server1
user#server2
user#server3
user#server4
The command will be:
parallel -k -a list.txt sshpass -e ssh {} 'uptime'

How to make shell script to automatically input value

I'm trying to copy ssh public key to all hosts on my network with the following little script
#!/bin/bash
for ip in $(nmap -n -sn 192.0.2.0/24 -oG - | awk '/Up$/{print $2}'); do
ssh-copy-id vagrant#$ip
done
However, it asks for the password for each IP, which count is unknown until execution of the script. How to make this script to automatically enter the password (which in this case is same for all the hosts)?
Use the sshpass. Note that it is not a good idea to store passwords in the scripts, but it will do the job for the setup:
#!/bin/bash
for ip in $(nmap -n -sn 192.0.2.0/24 -oG - | awk '/Up$/{print $2}'); do
sshpass -p password ssh-copy-id vagrant#$ip
done

Connect to multiple ssh connections through scripts

I have been trying to automatically enter a ssh connection using a script. This previous SOF post has helped me so far. Using one connection works (the first ssh statement). However, I want to create another ssh connection once connected, which I thought could look like this:
#! /bin/bash
# My ssh script
sshpass -p "MY_PASSWORD1" ssh -o StrictHostKeyChecking=no *my_hostname_1*
sshpass -p "MY_PASSWORD2" ssh -o StrictHostKeyChecking=no *my_hostname_2*
When running the script, I get only connected to the my_hostname_1 and the second ssh command is not run until I exit the first ssh connection.
I've tried using an if statement like this:
if [ "$HOSTNAME" = my_host_name_1 ]; then
sshpass -p "MY_PASSWORD2" ssh -o StrictHostKeyChecking=no *my_hostname_2*
fi
but I can't get any commands to be read until I exit the first connection.
Here is a ProxyCommand example as suggested by #lihao:
#!/bin/bash
sshpass -p "MY_PASSWORD2" ssh -o StrictHostKeyChecking=no \
-o ProxyCommand='sshpass -p "MY_PASSWORD1" ssh m_hostname_1 netcat -w 1 %h %p' \
my_hostname_2
You are proxying through the first host to get to the second. This assumes you have netcat installed on my_hostname_2. If not, you'll need to install it.
You can also set this up in your ~/.ssh/config file so you don't need the proxy stuff on the command line:
Host my_hostname_1
HostName my_hostname_1
Host my_hostname_2
HostName my_hostname_2
ProxyCommand ssh my_hostname_1 netcat -w 1 %h %p
However, this is a little trickier with the password handling. While you could put the sshpass here, it's not a great idea to have passwords in plain text. Using key based authentication might be better.
A Bash script is a sequence of commands.
echo moo
echo bar
will run echo moo and wait for it to complete, then run the next command.
You can run a remote command like this:
ssh remote echo moo
which will connect to remote, run the command, and exit. If there are additional commands in the script file after this, the shell which is executing these commands will continue with the next one, obviously on the host where you started the script.
To connect to one host from another, you could in principle do
ssh host1 ssh host2
but the proxy command suggested by #zerodiff improves on several aspects of the experience.

bash: while read loop - stop if there is variable sshpass

i have a problem with my bash script. I read line by line the variable lvm_path_exec, that works. I confirmed it with echo "lvmpath".
But as soon as i place a sshpass command into the while statement the script only process the first line which got grepped.
If there is no sshpass command all lines of lvmpath_exec get processed.
Do you see the error?
lvmpath_exec=$(sshpass -p "${password[$i]}" ssh ${user[$i]}#${ip[$i]} -p ${port[$i]} lvdisplay | grep datatest -A 3 | grep Path | awk '{ print $3 }')
echo "$lvmpath_exec" | while read lvmpath
do
lvmname=datatest
snap=_snapshot
snapname=$lvmname$snap
lvcreate=$(sshpass -p "${password[$i]}" ssh ${user[$i]}#${ip[$i]} -p ${port[$i]} lvcreate -L20G -s -n $snapname $lvmpath)
snap_path=$(sshpass -p "${password[$i]}" ssh ${user[$i]}#${ip[$i]} -p ${port[$i]} lvdisplay | grep $snapname -A 3 | grep Path | awk '{ print $3 }')
transfer=$(sshpass -p "${password[$i]}" ssh ${user[$i]}#${ip[$i]} -p ${port[$i]} "dd if=$snap_path | gzip -c" > /tmp/$snapname)
delsnap=$(sshpass -p "${password[$i]}" ssh ${user[$i]}#${ip[$i]} -p ${port[$i]} lvremove -f $snap_path)
done
UPDATE
I fixed it:
replace
echo "$lvmpath_exec" | while read lvmpath
with
for lvmpath in $lvmpath_exec
But shouldnt it work with while read too?
sshpass works by manipulating stdin to fool ssh into thinking it is getting the password from an interactive user. When you use a ... | while style loop, the loop iterates for every line coming from stdin, which sshpass wipes out after the first call, that's why only the first line gets executed. The for loop doesn't use stdin, that's why it doesn't have this problem.
As man sshpass explains, this tool is inherently insecure and you should really be using public key authentication instead. Also keep in mind that it has other ways of passing the password, using the -p flag is the least safe method of all, and any other method would be safer, for example the -e flag seems trivially easy. I know you might insist you have a legitimate use case, but this is so important I'm just gonna quote from the man page:
First and foremost, users of sshpass should realize that ssh's insis‐
tance on only getting the password interactively is not without reason.
It is close to impossible to securely store the password, and users of
sshpass should consider whether ssh's public key authentication pro‐
vides the same end-user experience, while involving less hassle and
being more secure.
The -p option should be considered the least secure of all of sshpass's
options. All system users can see the password in the command line
with a simple "ps" command. Sshpass makes a minimal attempt to hide the
password, but such attempts are doomed to create race conditions with‐
out actually solving the problem. Users of sshpass are encouraged to
use one of the other password passing techniques, which are all more
secure.
have you tried this..have not tried though
export SSHPASS=password[$i]
sshpass -e ssh -oBatchMode=no user[$i]#{ip[$i]} ..

Resources