Working with remote servers and scripting can be a bit of a pain, since every time you connect to a remote machine, it’s going to prompt you for your password! But, there’s a simple and quick way around this.. SSH Keys! This is a quick little trick to allow one machine to login to another, without needing to input a password.
1) Generate the SSH Keypair
Your first step is to generate a SSH key on the machine, and as the user you want to SSH From. To do this, you need to run the following command:
ssh-keygen -t rsa
Accept all the defaults of this command when prompted. The resulting key files need to end up in the .ssh directory inside the users home directory to work properly. DO NOT enter a passphrase! Simply press enter twice when prompted to leave it empty.
2) Upload your SSH Key to the remote server
Now that we’ve created a key, we need to tell the other host what it is, so that it will accept our connection without a password. To do this, run the following command:
scp ~/.ssh/id_rsa.pub <user>@<host>:.ssh/authorized_keys
Replace <user> with your username, and <host> with the remote server name in the command above.ย Be careful with the authorized_keys file. If you’ve done this before, that file will already exist, and you’ll need to manually add the key to the end of that file. Once you’ve uploaded this file, DO NOT change the permissions on it, or the .ssh directory, as that may break things for you and make SSH connections as that user difficult.
3) Lets test it out!
This part is simple… SSH to the remote server as the user, with the following command:
ssh <user>@<host> ls
This should produce a directory listing, but not prompt you for your password to do so. Replace <user> with your username, and <host> with the remote server name again of course. And that’s that! You can now script away to your hearts content, accessing your remote server, and not be prompted for a password!
Note:
If you already have SSH keys in your .ssh/authorized_keys file on the remote machine, you may wish to use the following command while uploading your SSH key instead of the one shown in step 2.
cat ~/.ssh/id_rsa.pub | ssh <user>@<host> 'dd of=.ssh/authorizedkeys oflag=append conv=notrunc'
This will prevent you from accidentally overwriting an existing key in the file.