通过脚本连接到多个ssh连接 [英] Connect to multiple ssh connections through scripts

查看:48
本文介绍了通过脚本连接到多个ssh连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用脚本自动输入ssh连接. 以前的SOF帖子到目前为止对我有帮助.使用一个连接有效(第一个 ssh 语句).但是,我想在连接后创建另一个ssh连接,我认为它看起来可能像这样:

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*

运行脚本时,我仅连接到 my_hostname_1 ,并且直到退出第一个 ssh 时,第二条 ssh 命令才运行连接.

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.

我尝试使用 if 语句,如下所示:

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.

推荐答案

这是@lihao建​​议的ProxyCommand示例:

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

您正在通过第一台主机进行代理,以到达第二台.假设您在 my_hostname_2 上安装了 netcat .如果没有,则需要安装它.

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.

您也可以在〜/.ssh/config 文件中进行设置,因此您不需要命令行上的代理内容:

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

但是,这在密码处理方面有些棘手.虽然您可以在此处放置 sshpass ,但以纯文本形式输入密码并不是一个好主意.使用基于密钥的身份验证可能会更好.

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.

这篇关于通过脚本连接到多个ssh连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆