Connecting to multiple ssh connections via scripts
I am trying to auto-inject ssh connection using a script. This previous SOF post helped me. Using a single connection works (first statement ssh
). However, I want to create another ssh connection after connecting, which I thought might 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 I run the script, I only connect to my_hostname_1
, and the second command ssh
doesn't run until I get out of the first connection ssh
.
I tried using the instruction if
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 to read any commands until I log out of the first connection.
source to share
Here's an example ProxyCommand 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 go to the second. It is assumed that on the my_hostname_2
set netcat
. If not, you need to install it.
You can also set this in your file ~/.ssh/config
so you don't need proxy files 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, it is a little more complicated with password processing. While you can put it sshpass
here, it's not a great idea to have passwords in plain text. Using key based authentication might be better.
source to share
A Bash script is a sequence of commands.
echo moo
echo bar
will start echo moo
and wait for it to complete, then run the following 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 that, the shell executing those commands will continue with the next one, obviously on the host where you ran the script.
To connect to one host from another, you could basically do
ssh host1 ssh host2
but the proxy command as suggested by @zerodiff improves some aspects of the experience.
source to share