Connect to multiple ssh connections through script

2019-05-10 05:40发布

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.

标签: bash shell
2条回答
来,给爷笑一个
2楼-- · 2019-05-10 05:56

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.

查看更多
倾城 Initia
3楼-- · 2019-05-10 06:11

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.

查看更多
登录 后发表回答