Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 558
Bob Risky Avatar asked Nov 02 '15 20:11

Bob Risky


People also ask

What is use of ~/ ssh config?

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.

Can PuTTY use ssh config file?

PuTTY cannot use OpenSSH configuration files.

What should be in ssh config?

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.

Where does ssh config go?

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 .


2 Answers

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.

like image 172
ghoti Avatar answered Sep 30 '22 02:09

ghoti


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.

like image 33
janos Avatar answered Sep 30 '22 01:09

janos