5

I have a server that has multiple "SSH daemons" running (actually Stash and OpenSSH), with different SSH keys needed for each. These daemons are listening on 2 different ports.

In the SSH config on clients (specifically ~/.ssh/config), is it possible to specify the port in the Host/Match directive (or some other way), so that I can override the IdentityFile based on port? That way ssh myserver -p 22 and ssh myserver -p 23 will both login using the correct keys, without additional configuration.

12

If your ssh client is new enough, you can use the config file Match keyword to have conditional configuration based on the target port.

Match host somehost exec "test %p = 42"
IdentityFile ...

The above example would only apply the "IdentityFile" line if the target host is "somehost" and the target port is 42. Match works like Host in that the lines following it (up to the next Match or Host line) only apply to sessions which match the criteria. In the example, the Match line checks that the host is "somehost", and it also runs an external command which is deemed to match if the command exits with status 0.

The command being run here is test %p = 42. "%p" will be replaced by the port value that ssh would use up to that point (either the default of 22 or the value from the command line). test is also known as [; it's a command-line utility mostly used in shell scripts as part of an if statement. Here, test is being used to test if the port number is 42.

The Match ssh_config keyword was added to OpenSSH in version 6.5 or 6.6. Check your ssh_config man page to see if it's available on your system.

| improve this answer | |
  • Oh wow! That's awesome. I assume it's pretty slow though. For a small amount of config using this though, probably not a big deal if it's a little slow. – Ricky Cook Mar 31 '15 at 23:37
  • I doubt the test takes any appreciable amount of time when compared to ssh crypto handshake. – studgeek Dec 16 '16 at 20:42
3

You can create host "aliases" of sorts in your ~/.ssh/config file that refer to SSH daemons on different ports of the same server. For example:

Host daemon1
HostName host.domain.com
Port 22
IdentityFile ~/.ssh/id_rsa_daemon1

Host daemon2
HostName host.domain.com
Port 23
IdentityFile ~/.ssh/id_rsa_daemon2

Then you can run ssh daemon1 or ssh daemon2 to log into a particular SSH daemon.

| improve this answer | |
  • Yeah, I had that idea too, but it needs to be transparent because there are a large number of deployment scripts that reference the hosts directly (which, I agree, should be parametarised but... yeah) – Ricky Cook Nov 13 '14 at 4:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.