How to copy SSH Key to a Remote Computer
CHUONG K. NGUYEN – BSc., MCSEx2, MCSAx2, MCP, MCTS, MCITP, CCNA
We can log into a remote Linux server either by a username / password combination or by using an SSH key. SSH keys provide a more secure way for the authentication to happen. Better yet, we can protect the key with a passphrase so that if the local computer (the one with the private key stored) is stolen, the person who has access to that computer cannot connect to the remote computer with just the key.
We essentially need to perform the following steps:
- Create the RSA key pair
- Store the keys (with or without passphrase)
- Copy the public key to the remote computer
- Remove root login.
This lab uses two computers running Ubuntu Linux 15.04.01
- LocalCom: 192.168.1.7
- RemoteCom: 192.168.1.8
- Elevate account privilage: sudo su
- Rename the server: hostnamectl set-hostname localcom
- Logoff: exit twice
- Log back in
- Change IP address: vi /etc/network/interfaces
Enable root login
Comment the line: PermitRootLogin without-password
Enter the line: PermitRootLogin yes
Restart SSHD: service ssh restart
Change Root Password: passwd root
Prepare Remotecom: do the same steps for RemoteCom but use IP address 192.168.1.8 and host name remotecom.
At this point, you can SSH to any of the two computers as root.
Step 1: Generate the RSA key Pair
ssh-keygen –t rsa
Step 2: Store the keys (and passphrase if there is any)
When asked for file name, keep the default one. Press Enter to leave the passphrase empty for the purpose of this lab. If you want to enter a passphrase, go ahead and do so but remember that every time you login using the keys, you will be prompted to enter the passphrase.
Step 3: Copy the public key to remotecom
cat ~/.ssh/id_rsa.pub | ssh firstname.lastname@example.org “mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys”
Here, I am going to use the first method. Confirm the connection, type “yes” and supply the root password for remotecom.
Now, from localcom, let’s login as email@example.com. You should be connected right away without a prompt for root password.
Disable Root Login with Password
Since we can login as root with the key, we should disable password login for root.
to do that, remove the comment for PermitRootLogin without-password. Also comment the line that says PermitRootLogin yes.
Restart SSH: service ssh restart
So when I try to SSH into remotecom as root on another computer, I got Access denied.
But I can SSH to remotecom from localcom.
As you can see, I now can SSH into remotecom from localcom without a password. SSH from anywhere else is not possible.