“Permission denied (publickey)” every time I try to push to git

gitsshterminal

I've recently faced a problem: each time I try to push to git repository (in my case, Bitbucket), I get that error:

$ git push origin master
git@bitbucket.org: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I've found a way to solve it by running these commands:

eval `ssh-agent`
ssh-add -l
ssh-add ~/.ssh/id_rsa

If I'll do this and then try to git push origin master, it'll work. But the problem is, this issue starts to appear after some time (probably after reboot, I'm not sure what causes it to appear again). UPD: it's most likely not caused by rebooting, cause I've just faced it 10 minutes after executing the code above, and got the same error. I didn't reboot my laptop since then.

What can cause such a behaviour and how can I fix this?

Best Answer

I think this happen because when you generated your ssh key, you entered a passphrase for security. When you start the ssh-agent and add ssh/rsa_id it should as for the passphrase.

[root@user xxxxx]# eval "$(ssh-agent -s)"
Agent pid 12082
[root@user xxxxx]# ssh-add /home/user/.ssh/id_rsa
Enter passphrase for /home/user/.ssh/id_rsa:
Identity added: /home/user/.ssh/id_rsa (/home/user/.ssh/id_rsa)

git push -u origin master
Counting objects: 94, done.