Millet Porridge

English version of https://corvo.myseu.cn

0%

OpenSSH Series 8: OpenSSH with alias

The last blog uses ssh fb-react01-teer.xx.yy.zz to log in to remote server. But do you notice that xx.yy.zz should not be entered by us either

machine name IP port user key
gg-android01-node.xx.yy.zz 48.132.144.01 22000 corvo ~/.ssh/id_rsa_test
gg-android02-node.xx.yy.zz 48.132.144.02 22000 corvo ~/.ssh/id_rsa_test
gg-android03-node.xx.yy.zz 48.132.144.03 22000 corvo ~/.ssh/id_rsa_test
gg-android04-node.xx.yy.zz 48.132.144.04 22000 corvo ~/.ssh/id_rsa_test
ms-vscode01-master.xx.yy.zz 42.188.144.01 22000 corvo ~/.ssh/id_rsa_test
ms-vscode02-master.xx.yy.zz 42.188.144.02 22000 corvo ~/.ssh/id_rsa_test
ms-vscode03-master.xx.yy.zz 42.188.144.03 22000 corvo ~/.ssh/id_rsa_test
fb-react01-teer.xx.yy.zz 59.143.138.01 22000 corvo ~/.ssh/id_rsa_test
fb-react02-teer.xx.yy.zz 59.143.138.02 22000 corvo ~/.ssh/id_rsa_test
fb-react03-teer.xx.yy.zz 59.143.138.03 22000 corvo ~/.ssh/id_rsa_test

What we really want?

We want to use ssh fb-react01-teer to log in.

How to implement?

Obviously, OpenSSH does not use the hostname to connect to the remote host, because TCP connections use IP addresses. OpenSSH does a DNS lookup first to convert fb-react03-teer.xx.yy.zz to 59.143.138.03.

What if we query the real IP address by an incomplete hostname and offer it to OpenSSH, it seems we can omit the .xx.yy.zz.

Get the IP address

There is a command in Linux called getent

1
2
3
4
5
6
7
# Use getent to get a record 
~ ❤ getent hosts fb-react01-teer.xx.yy.zz
59.143.138.01 fb-react01-teer.xx.yy.zz

# Use awk to get IP address
~ ❤ getent hosts fb-react01-teer.xx.yy.zz | awk '{print $1}'
59.143.138.01

Pass IP address to OpenSSH

There is another way to use ProxyCommand.

1
2
3
4
5
6
7
Host gg-* ms-* fb-*
ProxyCommand nc $(getent hosts %h.xx.yy.zz | awk '{print $1}') %p

Host gg-* ms-* fb-*
User corvo
Port 22000
IdentityFile ~/.ssh/id_rsa_test

This configuration will allow you to use ssh fb-react01-teer. A little wild, but very effective.

Extend ProxyCommand

You can see that the ProxyCommand helps us to use IP address directly. It gave me more inspiration.

Well, there are some hosts in the company whose exact names I don’t know — only addresses. So I create an alias for these hosts.

1
2
3
4
5
6
7
Host ttt-*
ProxyCommand nc $(sed -e "s/ttt-//g" <<< %h) %p

Host gg-* ms-* fb-* ttt-*
User corvo
Port 22000
IdentityFile ~/.ssh/id_rsa_test

It converts ttt-1.2.3.4 to 1.2.3.4, and you can use this command:

1
~ ❤  ssh ttt-1.2.3.4

Hope you enjoy this simple extension.