Reputation: 31
Imagine we a number of dynamic hosts of pattern
test-1.mydomain.com
test-2.mydomain.com
test-3.mydomain.com
...
test-n.mydomain.com
I'd like to SSH to each of those machines by not using full name (ssh test-7.mydomain.com
), but simply by doing ssh test-7
.
Is there a way to use SSH config to do pattern-like aliases like this?
Upvotes: 2
Views: 2260
Reputation: 4809
Yes, there is a way to do this directly in your ssh configuration.
Add this snippet to your ssh configuration ~/.ssh/config
:
# all test-* hosts should match to test-*.mydomain.example.com
host test-*
hostname %h.mydomain.example.com
You can verify this with the -G
flag to ssh. If your ssh is older and does not support -G
you can try parsing verbose ssh output.
# if your ssh supports -G
% ssh test-17 -G | grep hostname
hostname test-17.mydomain.example.com
# if your ssh does not support -G
% ssh -v -v test-n blarg >/dev/null 2>&1 | grep resolv
debug2: resolving "test-n.mydomain.example.com" port 22
ssh: Could not resolve hostname test-n.mydomain.example.com: Name or service not known
Ssh uses the first host line that matches. It is good practice to add your PATTERN host lines at the bottom of your configuration file.
If your test-n
name patterns contain only a single character suffix, then you can use a ?
pattern to make a less greedy match. test-?
will match test-1
test-a
test-z
but not test-10
Upvotes: 3
Reputation: 2093
If it is an option for you, you could add a search domain in the resolv.conf
file (I'm assuming you are on Linux).
You would need to add a line like this:
search mydomain.com
which will have SSH (and most other apps) look for test-n
, then test-n.mydomain.com
.
If you are not managing the resolv.conf
file yourself (if you use systemd-networkd or NetworkManager for example), you will have to ajust the search domains in their configuration files).
Upvotes: 0
Reputation: 686
You can create a ssh config file and pre setting your servers.
See this tutorial, i hope it helps you!
You can also create a function in your bash file for ssh access.
Like this:
function ssh_test () {
[[ $1 =~ ^('test-1'|'test-2'|'test-3')$ ]] || { echo 'Not a valid value !!' && return ;}
domain=$1.mydomain.com
ssh my_user@"$domain"
}
Upvotes: 0