/home/kroq-gar78/

Jan 07, 2013

SSH Using Hostnames

I've always been wondering why I couldn't use hostnames in my ssh commands (like ssh pi@raspberrypi), so I've been using IP addresses the entire time (e.g. ssh pi@192.168.1.31). Today, I've finally figured out how to use easier-to-remember hostnames in Linux, and the good thing is that it's pretty simple to do.

/etc/hosts

Quickly, a short disclaimer: This tutorial only works for Debian-based systems. This includes Ubuntu, Mint, and Raspbian and their derivatives. The file we need to edit to get this to work is the /etc/hosts file. First, we should probably back up the file.

sudo cp /etc/hosts /etc/hosts_$(date +%F)

Open the file:

sudoedit /etc/hosts

Now, we need to add the computer with the hostname we want to associate it with in this format:

<IP address>    <hostname>

Put it after the two lines about "127.0.0.1" and "127.0.1.1". So, for my Raspberry Pi:

192.168.1.31 raspberrypi

Test it!

Now, we just need to make sure it works. So, for my Raspberry Pi, this:

ssh pi@192.168.1.31

becomes:

ssh pi@raspberrypi

Pretty easy, right? Well, the only "gotcha" is that the machine has to have a static IP address for it to work well. Otherwise, you'll have to update it every time the target machine is assigned a new IP address.

Thanks for reading! :)

References