SSH by hostname over LAN
Table of Contents
Objective
It is often necessary to SSH into a remote machine (e.g. a server) and it is much more convenient to do so by a hostname instead of an IP address. This is similar to the use case explored in the article on how to set the IP address and hostname of a Vagrant VM instance, except that in this case we are using an actual machine.
Setup
This article uses a simple area network with the following:
- a desktop running Arch Linux with hostname desktop.my.domain
- a laptop running FreeBSD with hostname laptop.my.domain
- a non-root user alice@desktop
- a non-root user bob@laptop
- a D'Link DSL-2730U ADSL router
The desktop is wired to the ADSL router whereas the laptop is connected to the latter wireless. The ADSL router also serves as a DHCP server, assiging IP addresses to the desktop and laptop
Procedure
We want to connect to bob@laptop from alice@desktop.
Assign reserved DHCP address
A reserved DHCP address will allow an entry to be written in the /etc/hosts file that maps a hostname to an IP address. In this case, we want to map the IP address 192.168.1.5 to laptop.my.domain. The following steps are particular to the D'Link ADSL router, but the steps would be similar for other routes
Determine MAC address
Add reserved DHCP entry
Save and reboot
Add record in hosts file
Copy SSH ID
ssh-copy-id -i ~/.ssh/id_rsa.pub bob@laptop.my.domain
Since this is the first time we are connecting over SSH to bob@laptop.my.domain, ssh-copy-id will ask us to confirm if we want to connect. Once confirmed, bob's password will be asked.
#+RESULTS
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/alice/.ssh/id_rsa.pub" The authenticity of host 'laptop.my.domain (192.168.1.5)' can't be established. ED25519 key fingerprint is <redacted>. This key is not known by any other names Are you sure you want to continue connecting (yes/no/[fingerprint])? yes /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys (bob@laptop.my.domain) Password for bob@laptop.my.domain: Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'bob@laptop.my.domain'" and check to make sure that only the key(s) you wanted were added
Results
We should now be able to SSH to bob@laptop from alice@desktop:
ssh bobk@laptop.my.domain
To avoid having to type the FQDN every time, we can instead connect as:
ssh bob@laptop
For the first time connecting, a challenge would be issued:
#+RESULTS
The authenticity of host 'laptop (192.168.1.5)' can't be established.
ED25519 key fingerprint is <redacted>.
This host key is known by the following other names/addresses:
~/.ssh/known_hosts:62: laptop.my.domain
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'laptop' (<redacted>) to the list of known hosts.