1

Imagine we have dynamic number of hosts of pattern

test-1.mydomain.com
test-2.mydomain.com
test-3.mydomain.com
...
test-n.mydomain.com

I'd like to ssh on each of those machines by not using full name

ex. 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??

3 Answers3

1

Yes!

Yes, there is a way to do this directly in your ssh configuration.

  1. host allows PATTERNS
  2. hostname allows TOKENS

How:

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

Verify:

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

Notes:

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

spazm
  • 4,399
  • 31
  • 30
0

You can create a ssh config file and pre setting your servers.

See this tutorial, i hope it helps you!

ssh config

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" 
}
0

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).

Simon Doppler
  • 1,918
  • 8
  • 26