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.
A Bash script is a sequence of commands.
will run
echo moo
and wait for it to complete, then run the next command.You can run a remote command like this:
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
but the proxy command suggested by @zerodiff improves on several aspects of the experience.
Here is a ProxyCommand example as suggested by @lihao:
You are proxying through the first host to get to the second. This assumes you have
netcat
installed onmy_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: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.