Link SSH Private Key to Specific Host in Ubuntu Config
Managing multiple SSH keys for different servers can be challenging,
but Ubuntu allows you to automate this process using the SSH client
configuration file. This article explains how to configure your local
SSH client to automatically map a specific private key file to a
designated remote host, eliminating the need to manually specify the key
path using the -i flag every time you connect.
Step 1: Locate or Create Your SSH Config File
The SSH configuration settings for your user account are stored in a
file named config inside your hidden .ssh
directory.
Open your terminal and check if the file exists, or create it if it does not, by running:
touch ~/.ssh/configNext, ensure the file has the correct permissions so that only your user can read and write to it. Secure the file with this command:
chmod 600 ~/.ssh/configStep 2: Edit the Config File
Open the configuration file in a text editor like Nano:
nano ~/.ssh/configStep 3: Add the Host Configuration Block
Add a new configuration block using the following format. Replace the placeholders with your actual server details and the path to your private key:
Host my-remote-server
HostName 192.168.1.50
User ubuntu
IdentityFile ~/.ssh/id_rsa_custom
IdentitiesOnly yes
Here is what each directive means: * Host: A
nickname or alias of your choice. You will type this name to initiate
the connection. * HostName: The actual IP address or
domain name of the remote server. * User: The remote
username you want to log in as. * IdentityFile: The
absolute path to the specific private key file you want to use for this
host. * IdentitiesOnly: Set to yes to
force SSH to only use the key specified in the IdentityFile
directive, preventing it from trying other keys stored in your SSH
agent.
Save and exit the editor (in Nano, press Ctrl+O,
Enter, then Ctrl+X).
Step 4: Connect to the Host
Once the configuration is saved, you no longer need to type the full username, IP address, or path to the key. Connect to your server simply by typing:
ssh my-remote-server