Connect to multiple ssh connections through scripts - bash

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.

Related

Execute commands after sshpass login in the script

I'm an Ubuntu bash newbie. I successfully login to an sFTP server using sshpass. But once the connection is established I also need to download a directory from the server. My script cannot seem to pass the connection line though. This is what I have in my script (.sh) file:
#!/bin/bash
sshpass -p 'MY_PASSWORD' sftp -o StrictHostKeyChecking=no -o HostKeyAlgorithms=+ssh-dss MYUSER#MYSFTPSERVERADDRESS
echo "hello"
get -r Export
In the snipped above, my echo and my get are not executed. The terminal is waiting for my input with a sftp> prompt.
You would be better served using scp instead of sftp and sharing keys instead of putting the password in a script if you're able, but if you must use sftp for some reason, it can take its commands from a heredoc like:
sshpass -p 'MY_PASS' sftp -o StrictHostKeyChecking=no -o HostKeyAlgorithms=+ssh-dss MYUSER#MYSFTPSERVERADDRESS <<EOF
get -r Export
EOF
note that echo isn't a valid sftp command.
You can put whatever commands you want sftp to execute before the EOF and it will do them each in turn.
If all you want is to get that directory it's probably still simpler to use scp if you can:
sshpass -p 'MY_PASSWORD' scp -o StrictHostKeyChecking=no -o HostKeyAlgorithms=+ssh-dss -r MYUSER#MYSFTPSERVERADDRESS:Export .

Capture output of double-ssh (ssh twice) session as BASH variable

I'd like to capture the output of an ssh session. However, I first need to ssh twice (from my local computer to the remote portal to the remote server), then run a command and capture the output.
Doing this line-by-line, I would do:
ssh name#remote.portal.com
ssh remote.server.com
remote.command.sh
I have tried the following:
server=remote.server.com ##define in the script, since it varies
sshoutput=$(ssh -tt name#remote.portal.com exec "ssh -tt ${server} echo \"test\"")
echo $sshoutput
I would expect the above script to echo "test" after the final command. However, the outer ssh prompt just hangs after I enter my command and, once I Ctrl+c or fail to enter my password, the inner ssh session fails (I believe since stdout is no longer printed to screen and I no longer get my password prompt).
If I run just the inner command (i.e., without "sshoutput=$(" to save it as a variable), then it works but (obviously) does not capture output. I have also tried without the "exec".
I have also tried saving the inner ssh as a variable like
sshoutput=$(ssh -tt name#portal myvar=$(ssh -tt ${server} echo \"test\"") && echo $myvar)
but that fails because BASH tries to execute the inner ssh before sending it to the outer ssh session (I believe), and the server name is not recognized.
(I have looked at https://unix.stackexchange.com/questions/89428/ssh-twice-in-bash-alias-function but they simply say "more flags required if using interactive passwords" and do not address capturing output)
Thanks in advance for any assistance!
The best-practice approach here is to have ssh itself do the work of jumping through your bouncehost.
result=$(ssh \
-o 'ProxyCommand=ssh name#remote.portal.com nc -w 120 %h %p' \
name#remote.server.com \
"remote.command.sh")
You can automate that in your ~/.ssh/config, like so:
Host remote.server.com
ProxyCommand ssh name#remote.portal.com nc -w 120 %h %p
...after which any ssh remote.server.com command will automatically jump through remote.portal.com. (Change nc to netcat or similar, as appropriate for tools that are installed on the bouncehost).
That said, if you really want to do it yourself, you can:
printf -v inner_cmd '%q ' "remote.command.sh"
printf -v outer_cmd '%q ' ssh name#remote.server.com "$inner_cmd"
ssh name#remote.portal.com bash -s <<EOF
$outer_cmd
EOF
...the last piece of which can be run in a command substitution like so:
result=$(ssh name#remote.portal.com bash -s <<EOF
$outer_cmd
EOF
)

Auto answer ssh-copy-id in shell script

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.

How to copy echo 'x' to file during an ssh connection

I have a script which starts an ssh-connection.
so the variable $ssh start the ssh connection.
so $SSH hostname gives the hostname of the host where I ssh to.
Now I try to echo something and copy the output of the echo to a file.
SSH="ssh -tt -i key.pem user#ec2-instance"
When I perform a manual ssh to the host and perform:
sudo sh -c "echo 'DEVS=/dev/xvdbb' >> /etc/sysconfig/docker-storage-setup"
it works.
But when I perform
${SSH} sudo sh -c "echo 'DEVS=/dev/xvdb' > /etc/sysconfig/docker-storage-setup"
it does not seem to work.
EDIT:
Also using tee is working fine after performing an ssh manually but does not seem to work after the ssh in the script.sh
The echo command after an ssh of the script is happening on my real host (from where I'm running the script, not the host where I'm performing an ssh to). So the file on my real host is being changed and not the file on my host where I've performed an ssh to.
The command passed to ssh will be executed by the remote shell, so you need to add one level of quoting:
${SSH} "sudo sh -c \"echo 'DEVS=/dev/xvdb' > /etc/sysconfig/docker-storage-setup\""
The only thing you really need on the server is the writing though, so if you don't have password prompts and such you can get rid of some of this nesting:
echo 'DEVS=/dev/xvdb' | $SSH 'sudo tee /etc/sysconfig/docker-storage-setup'

How to put sshpass command inside a bash script?

I am trying to run a sshpass command inside a bash script but it isn't working.
If I run the same command from the terminal it works fine but running it in a bash script it doesn't.
#! /bin/bash
sshpass -p 'password' ssh user#host command
I am aware of the security issues but its not important now.
Can someone help? Am I missing something.
Thanks
Try the "-o StrictHostKeyChecking=no" option to ssh("-o" being the flag that tells ssh that your are going to use an option). This accepts any incoming RSA key from your ssh connection, even if the key is not in the "known host" list.
sshpass -p 'password' ssh -o StrictHostKeyChecking=no user#host 'command'
Do which sshpass in your command line to get the absolute path to sshpass and replace it in the bash script.
You should also probably do the same with the command you are trying to run.
The problem might be that it is not finding it.
1 - You can script sshpass's ssh command like this:
#!/bin/bash
export SSHPASS=password
sshpass -e ssh -oBatchMode=no user#host
2 - You can script sshpass's sftp commandlike this:
#!/bin/bash
export SSHPASS=password
sshpass -e sftp -oBatchMode=no -b - user#host << !
put someFile
get anotherFile
bye
!
I didn't understand how the accepted answer answers the actual question of how to run any commands on the server after sshpass is given from within the bash script file. For that reason, I'm providing an answer.
After your provided script commands, execute additional commands like below:
sshpass -p 'password' ssh user#host "ls; whois google.com;" #or whichever commands you would like to use, for multiple commands provide a semicolon ; after the command
In your script:
#! /bin/bash
sshpass -p 'password' ssh user#host "ls; whois google.com;"
This worked for me:
#!/bin/bash
#Variables
FILELOCAL=/var/www/folder/$(date +'%Y%m%d_%H-%M-%S').csv
SFTPHOSTNAME="myHost.com"
SFTPUSERNAME="myUser"
SFTPPASSWORD="myPass"
FOLDER="myFolderIfNeeded"
FILEREMOTE="fileNameRemote"
#SFTP CONNECTION
sshpass -p $SFTPPASSWORD sftp $SFTPUSERNAME#$SFTPHOSTNAME << !
cd $FOLDER
get $FILEREMOTE $FILELOCAL
ls
bye
!
Probably you have to install sshpass:
sudo apt-get install sshpass

Resources