animesh
By:
animesh

Error Permission denied (publickey) when I try to ssh

March 16, 2017 157 views
DigitalOcean Debian

Recently I threw out my old linux laptop and set everything up again in my new laptop. The only trouble I have now is not being able to log in to my DO instance via ssh. This instance had one ssh key setup before and in the sshd config it had permitrootlogin set to no. So I created a new ssh key to be able to login from this new laptop.

$ ssh-keygen -t rsa -C "gitlab" -b 4096

Then added the public key this to the instance. Now I try to login

$ ssh user@server

I get asked password for this user. I am able to login using the password. This isn't how I was logging in before. I used to type my ssh passphrase. So I thought this may be because this is a new key and I disabled password authentication in sshd config. After this, I get the error

$ ssh user@server
Permission denied (publickey)

I checked online and set the permission to .ssh folder to 700. Still I get the same error. I can access the online console of the instance, but don't know what to do.

How do I resolve this?

2 Answers

@animesh

When you create a user using useradd, you'll need to specify their home directory or use usermod to change it (as would be the case if the user already exists).

What I normally do is create the directories first:

mkdir -p /home/myuser/.ssh

Create the authorized_keys file:

touch /home/myuser/.ssh/authorized_keys

Then add the user:

useradd -d /home/myuser myuser

Set proper permissions:

chmod 700 /home/myuser/.ssh
chmod 644 /home/myuser/.ssh/authorized_keys

Set ownership:

chown -R myuser:myuser /home/myuser/*

Once that's done, you should be able to login with myuser.

If you already have a user:

usermod -d /home/myuser myuser

and then continue with the above.

@jtittle
I have done all the above steps in my local machine and I still get the same error.

Permission denied (publickey)

Should this be done in my DO instance? If so, I remember seeing a authorized_keys file in the .ssh folder with some contents already presumably from the first time setup.

Should I append my publickey onto the authorized_keys file in the DO instance?

Have another answer? Share your knowledge.