Regular Expression matching in ssh config
Solution 1:
This should do the trick on OpenSSH 5.5 and greater.
Host *.*
Hostname %h
Host *
Hostname %h.domain.com
IdentityFile /path/to/keyfile.pem
The first rule matches any normal domain names and just passes the domain name through. The second rule handles single word hosts and appends domain.com to the end.
One side effect of this is that even for ssh calls to anotherdomain.com, ssh will try to use the IdentityFile for domain.com. I don't think that matters however.
Solution 2:
This sounds like a problem best solved by DNS. Add this to your
/etc/resolv.conf
:search domain.com
If a DNS lookup contains no dots1 or returns an NXDOMAIN >response then another DNS lookup will be made with that search value >appended.
Examples:
If you do
ssh srv1
, the DNS lookup will be made forsrv1.domain.com
.If you do
ssh srv1.dc1
, the DNS lookup will be forsrv1.dc1
which will return NXDOMAIN. The automatic followup DNS lookup will be forsrv1.dc1.domain.com
.You can add multiple search domains to that line separated by whitespace and they will be tried in the order listed until one of them returns an A record2.
1.) This value is configurable and refers to the number of dots the short name must have fewer than. The default value is 1 and it should be set higher than 1 for sites where the hosts are of the form
srv1.dc1.domain.com
. This avoids the useless request to the root servers for thedc1
top level domain.2.) Or an AAAA record.
Updated answer 25th Nov 2020:
Although the outdated answer above is still a fully valid one, nowadays, I would rather suggest using the ssh_config
built-in mechanism CanonicalDomains
That would mean, instead of changing /etc/resolv.conf
or DNS records, you can simply add the following lines to the top of your ssh_config
file:
CanonicalizeHostname yes
CanonicalDomains domain.com
Please refer to the official ssh_config documentation for details around these configuration statements.
Solution 3:
You can use ProxyCommand
to use regex
on the host name specified on the command line.
Host srv*.domain.com
User amac
ProxyCommand nc $(sed -e "s/.domain.com//" <<< "%h") %p
IdentityFile /home/amac/.ssh/id_rsa
Now ssh srv23.domain.com
would connect to srv23
.
Note, you don't need to specify HostName
.