I am writing an SSH config file and want to perform a bit of logic. For example:
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!
User-specific OpenSSH file client configuration ~/. ssh/config or $HOME/. ssh/config : This is user's own configuration file which, overrides the settings in the global client configuration file, /etc/ssh/ssh_config.
PuTTY cannot use OpenSSH configuration files.
The contents of the SSH client config file is organized into stanzas (sections). Each stanza starts with the Host directive and contains specific SSH options used when establishing a connection with the remote SSH server. Indentation is not required but is recommended since it makes the file easier to read.
The ssh program on a host receives its configuration from either the command line or from configuration files ~/. ssh/config and /etc/ssh/ssh_config .
Your ProxyCommand
can be a shell script.
host myhost1 ProxyCommand $HOME/bin/selecthost %h %p
And then in ~/bin/selecthost
:
#!/usr/bin/env bash hosts=(bastion1 bastion2) onehost=${hosts[$RANDOM % ${#hosts[@]}]} ssh -x -a -q ${2:+-W $1:$2} $onehost
Untested. Your mileage may vary. May contain nuts.
Per comments, I've also tested the following, and it 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. You could add that to the logic of a separate shell script if your SSH config matches multiple hosts in the same host
entry.
In ~/.ssh/config
you 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.
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:
ProxyCommand sudo /root/bin/ssh-randomly.sh [bastion_host1] [bastion_host2]
And write a Bash script /root/bin/ssh-randomly.sh
to take two hostname parameters, select one of them randomly, and run the real ssh
command with the appropriate parameters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With