DEV Community

muhadmr
muhadmr

Posted on

Adding Existing SSH Key to git via command line

My environment

  • windows 11
  • using git extension with git bash
  • ssh key was generated using PuttyGen

Problem

  • cannot push because of permission issue
λ git push --set-upstream origin main git@gitlab.com: Permission denied (publickey). fatal: Could not read from remote repository. 
Enter fullscreen mode Exit fullscreen mode

Solution

  • Add the existing key to git

  • use ssh-add to add key, however, ssh-add requires ssh-agent to be running. (if in linux running eval "$(ssh-agent -s)" will allow next command ssh-agent to be executed directly, but on windows the command is not recognized)

λ eval "$(ssh-agent -s)" 'eval' is not recognized as an internal or external command, operable program or batch file. 
Enter fullscreen mode Exit fullscreen mode
  • so we need to get the ssh-agent socket and pid info
λ ssh-agent SSH_AUTH_SOCK=/tmp/ssh-YKsmNCSnWFXo/agent.837; export SSH_AUTH_SOCK; SSH_AGENT_PID=838; export SSH_AGENT_PID; echo Agent pid 838; 
Enter fullscreen mode Exit fullscreen mode
  • next, set the environment. Note the SSH_AUTO_SOCK and SSH_AGENT_PID must be the same as above
λ set SSH_AUTH_SOCK=/tmp/ssh-YKsmNCSnWFXo/agent.837 λ set SSH_AGENT_PID=838 
Enter fullscreen mode Exit fullscreen mode
  • now use the command ssh-add to add new key
λ ssh-add c:\Keys\newKey Identity added: c:\Keys\newKey 
Enter fullscreen mode Exit fullscreen mode
  • however, my other key is generated using puttygen with old openssh format. so I need to convert the key to new format.

  • run puttygen and select the conversions menu -> export openssh key (force new format)

Image description

  • then run the ssh-add again
λ ssh-add c:\Keys\gitprivatekey-new Identity added: c:\Keys\gitprivatekey-new 
Enter fullscreen mode Exit fullscreen mode
  • then run git push again
λ git push --set-upstream origin main Enumerating objects: 2370, done. Counting objects: 100% (2370/2370), done. Delta compression using up to 12 threads 
Enter fullscreen mode Exit fullscreen mode
  • use the command ssh-add -l to list existing identities
λ ssh-add -l 2048 SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx user1 (RSA) 2048 SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx rsa-key(RSA) 
Enter fullscreen mode Exit fullscreen mode
  • done

Top comments (0)