Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to login to sever using SSH key
  1. SSH Key

If you don’t (yet) have a SSH-key on your local workstation you need to create one. A SSH-key provides a safe way to connect with another computer. It exists of two parts: a private and a public key. The private key is stored on your local workstation, and the public key is put on the machine you wish to connect with. To create a SSH-key on your local workstation you must enter the following command:

$ ssh-keygen -t rsa -C 'name@domain.com'
$ ssh-keygen -t rsa -C 'name@domain.com'
```
Of course you fill in your own e-mail address here. A couple of questions are asked like where to store the key and which password you want to use.
With the next command you can read your public key (and copy/paste it to your clipboard):

```
$ ssh-add -L
$ ssh-add -L
```

2. User account on the server

On the remote server you can add a new user, or you can add your public key to an existing user. This user is going to be used as the UNIX-user for copying files and creating directories. If you want to create a new account this can be done as following:


$ adduser deploy
$ passwd -l deploy
1
2
$ adduser deploy
$ passwd -l deploy
The second command makes sure the user is ‘locked’. This means that the user cannot login on the server with the usual username/password-method, but only with SSH-keys.

3. Add your public key

On the server, make sure you’re logged in as your deployment-user (‘deploy’) in our example. In his home-directory, create a folder called .ssh  (if it doesn’t already exist), and in this folder create a file called authorized_keys . In this file you can paste your public key. Make sure the rights of authorized_keys  are set to 0600 and that of the .ssh -folder to 0700:

```
$ su deploy
$ cd ~
$ mkdir .ssh
$ echo "(public key)" >> .ssh/authorized_keys
$ chmod 0700 .ssh
$ chmod 0600 .ssh/authorized_keys
$ su deploy
$ cd ~
$ mkdir .ssh
$ echo "(public key)" >> .ssh/authorized_keys
$ chmod 0700 .ssh
$ chmod 0600 .ssh/authorized_keys
```
If all went well, you will now be able to login with SSH on this server, without being prompted for a password. You can test this by trying to connect to the server from your local machine. If you’re not being prompted for a password, you did it right:

```
$ ssh deploy@ssh.myserver.com
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment