Ssh – .ssh/config ProxyCommand with a variable port

opensshsshssh-configssh-tunneling

In the environment I work in, we use tunnels to SSH to various servers. For example, I'll 'ssh -p XXXXX username@localhost' to reach the server.

If the port was always the same, I could do this, and I'd be done:

Host somehost
  User bryan
  Hostname localhost
  Port 12345
  ProxyCommand ssh -p 2218 bryan@first.server.com -W %h:%p

However, the port used can and will change if the tunnel goes down and comes back up. This isn't something I have the ability to change – it's built into the infrastructure. So, I wrote a program to find the current port. But I don't know how to either:

a) Run that program and use the output for the %p variable; or
b) Run a cron job on first.server.com to write out a text file with the port in it, or set an environment variable, or something.

In effect, I want to do this. Is it possible?

Host somehost
  User bryan
  Hostname localhost
  Port `sh get_port_for_somehost.sh`
  ProxyCommand ssh -p 2218 bryan@first.server.com -W %h:%p

The only thing I can think of right now is to run a program on my laptop which rewrites my .ssh/config after going and querying what the ports currently are, but I'd prefer not to do that.

Best Answer

It is not possible to write a script in the configuration file to pull a variable for port number.

But you can write a bash function to get the port for you and place it into the correct place. For example place the following to the ~/.bashrc:

function ssh-dynamic() {
  PORT=`sh get_port_for_somehost.sh`
  exec ssh -p "$PORT" somehost "$@"
}

where the other configuration may stay in the ~/.ssh/config.

Related Question