bash ~/.ssh/config 文件可以使用变量吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33486339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:51:47  来源:igfitidea点击:

Can an ~/.ssh/config file use variables?

bashsshconfig

提问by Bob Risky

I am writing an SSH config file and want to perform a bit of logic. For example:

我正在编写一个 SSH 配置文件并想要执行一些逻辑。例如:

Host myhost1
    ProxyCommand ssh -A {choose randomly between [bastion_host1] and [bastion_host2]} -W %h:%p

Is it possible to achieve the above using (bash?) variables? Thanks!

是否可以使用(bash?)变量来实现上述目的?谢谢!

采纳答案by ghoti

Your proxycommand can be a shell script.

您的代理命令可以是一个 shell 脚本。

host myhost1
    ProxyCommand $HOME/bin/selecthost %h %p

And then in ~/bin/selecthost:

然后在~/bin/selecthost

#!/usr/bin/env bash

hosts=(bastion1 bastion2)

onehost=${hosts[$RANDOM % ${#hosts[@]}]}

ssh -x -a -q ${2:+-W :} $onehost

Untested. Your milage may vary. May contain nuts.

未经测试。您的里程可能会有所不同。可能含有坚果。



Update:

更新:

Per comments, I've tested the following, and it also works nicely:

根据评论,我已经测试了以下内容,并且效果很好:

host myhost1 myhost2
    ProxyCommand bash -c 'hosts=(bastion1 bastion2); ssh -xaqW%h:22 ${hosts[$RANDOM % ${#hosts[@]}]}'

Of course, this method doesn't allow you to specify a custom port per host, which you could add to the logic of a separate shell script if required for multiple hosts in the same hostentry in your ssh config.

当然,此方法不允许您为每个主机指定自定义端口,如果hostssh 配置中的同一条目中的多个主机需要,您可以将其添加到单独的 shell 脚本的逻辑中。

回答by janos

In ~/.ssh/configyou cannot have much logic, and no Bash. The manual for this file is in man ssh_config, and it makes no mention of such feature.

~/.ssh/config你不能有太多的逻辑,并没有击。该文件的手册在 中man ssh_config,并没有提及该功能。

What you can do is create a script that will have the logic you need, and make you ssh configuration call that script. Something along the lines of:

您可以做的是创建一个具有您需要的逻辑的脚本,并使您的 ssh 配置调用该脚本。类似的东西:

ProxyCommand sudo /root/bin/ssh-randomly.sh [bastion_host1] [bastion_host2]

And write a Bash script /root/bin/ssh-randomly.shto take two hostname parameters, select one of them randomly, and run the real sshcommand with the appropriate parameters.

并编写一个 Bash 脚本/root/bin/ssh-randomly.sh,取两个主机名参数,随机选择其中一个,并ssh使用适当的参数运行真正的命令。

回答by chepner

No; .ssh/configis not processed by any outside program. You'll need a shell function along the lines of

不; .ssh/config不被任何外部程序处理。您将需要一个 shell 函数

ssh () {
    (( $RANDOM % 2 )) && bastion=bastion_host1 || bastion=bastion_host2

    command ssh -A "$bastion" "$@"
}