Ssh – How to set up ssh config file (~/.ssh/config) to recognise /etc/hosts host names

ssh

I have added the following line (with a different IP) into the /etc/hosts file:

192.168.0.4      my_pc

Likewise the ~/.ssh/config file has the following entry in it:

Host 192.168.0.*
IdentityFile ~/id_rsa

Sending a ping to my_pc, sends a ping to 192.168.0.4 as intended. I can also ssh into the machine using ssh user@192.168.0.4. If I try ssh user@my_pc, the authentication fails as the key is not used.

How to set up ssh so that /etc/hosts is recognised?
I know that a host name can be done in ~/.ssh/config however is there a way to keep the host name out of that file and have it match the IP to /etc/hosts?

Best Answer

You don't need to use /etc/hosts file to connect user@my-pc. Add following lines to ~/.ssh/config

Host my-pc
     Hostname 192.168.0.4
     Port 22
     User john
     IdentityFile ~/id_rsa

So now when you just type ssh my-pc it will connect to john@192.168.0.4

I have made to myself a little script to make adding new hosts as fast as possible, you may use it aswell ;)

#!/bin/bash
#Made by Gen Lee ^.^
#######
#Adds new host to ~/.ssh/config
ver="Ezy SSH v0.1"

#Colors:
red='\033[01;31m'
norm='\033[00m'

echo "Started $ver"
  # Questions
    echo -en "Enter ${red}host${norm}: "
    read config_host
    echo -en "Enter ${red}domain${norm}/${red}ip${norm}: "
    read config_hostname
    echo -en "Enter ${red}port${norm} (${red}22${norm}): "
    read config_port
    echo -en "Enter ${red}username${norm} (${red}root${norm}): "
    read config_user
    echo -en "Enter ${red}private key location${norm}: "
    read config_key

  # Checking information
    check_host=$(awk "/^Host $config_host$/" ~/.ssh/config)
    if [ ! $check_host ]; then
      sleep 0
    else
      echo -e "You already have following host (${red}$config_host${norm})!"
      exit 0
    fi
    if [ ! $config_port ]; then
      config_port="22"
    fi
    if [ ! $config_user ]; then
      config_user="root"
    fi
    test -f $config_key
    if [ $? -eq 1 ]; then
      echo "Private key location is invalid!"
      exit 0
    fi

  # Adding parameters to ~/.ssh/config
    echo "" >> .ssh/config
    echo "Host $config_host" >> ~/.ssh/config
    echo -e "\t Hostname $config_hostname" >> ~/.ssh/config
    echo -e "\t Port $config_port" >> ~/.ssh/config
    echo -e "\t User $config_user" >> ~/.ssh/config
    if [ ! $config_key ]; then
      sleep 0
    else
      echo -e "\t IdentityFile $config_key" >> .ssh/config
    fi
echo "All done! ^.^"
exit 0