Ssh – How to get the Host value inside ~/.ssh/config

ssh

Within a ~/.ssh/config or ssh_config file, %h will give you the HostName value, but how do you get the Host ("alias") value?

Why would I want to do that? Well, here's an example

  Host some_host_alias
    HostName 1.2.3.4
    User my_user_name
    PasswordAuthentication no
    IdentityFile ~/.ssh/some_host_alias.rsa.id
    LocalCommand some_script.sh %h    # <---- this is the critical line

If I pass %h to the script, then it uses 1.2.3.4, which fails to give it all the options it needs to connect to that machine. I need to pass some_host_alias, but I can't find the % variable for that.

(And: yes! I'm aware of the risk of recursion. That's solved inside the script.)


UPDATE: Kenster pointed out that I could just hard-code the Host value as an argument to the script. Of course this will work in the example I gave, but it won't work if I'm using pattern matching for the Host.

Best Answer

I'm not sure which version it was added, but I think you want to use %n instead of %h. From the ssh_config(5) manpage:

LocalCommand
    Specifies a command to execute on the local machine after successfully
    connecting to the server. The command string extends to the end of the
    line, and is executed with the user's shell. The following escape character
    substitutions will be performed: ‘%d’ (local user's home directory), ‘%h’
    (remote host name), ‘%l’ (local host name), ‘%n’ (host name as provided on
    the command line), ‘%p’ (remote port), ‘%r’ (remote user name) or ‘%u’
    (local user name).