ChatGPT解决这个技术问题 Extra ChatGPT

SSH Key - Still asking for password and passphrase

I've been somewhat 'putting up' with Github always asking for my username and password when I clone a repository. I want to bypass this step because it is an annoyance within my workflow.

I tried setting up an SSH key (which I successfully did) using this guide. https://help.github.com/articles/generating-ssh-keys and I was successful.

My problem is that I am still asked for my github password and passphrase when cloning a repository (using SSH). My understanding was that after I set up this SSH key, I would no longer have to do that.

I am a little unsure what to ask, so I will just state my goal.

I want to be able to clone repositories without having to put in my Github information all the time.

What am I missing with my SSH key? If anyone can provide some guidance or resources I would appreciate it, because I've always felt a little lost when it came to SSH authentication in GitHub.

From my knowledge, this is a command that tests if things are working properly, here are the output from my console:

~ $ ssh -T git@github.com
Saving password to keychain failed
Enter passphrase for key '/Users/MYNAME/.ssh/id_rsa':
Hi MYNAME! You've successfully authenticated, but GitHub does not provide shell access.

When I input my password, should that fail first? Then, when I enter my passphrase, it passes.

In which OS are you? A modern Linux Desktop would propose to store your passphrase in a keyring manager. Same in Mac OS X. In Windows you can use pageant, which is part of putty. In all these the goal is the same: you enter the passphrase only once after you start your PC, the key manager agents will pass it to ssh in subsequent uses until you reboot.
I'm a little late to the party here, but on the little clone tab/button in github there is a link that says "Use SSH". You want to do that. It changes your clone link to something like "git@github:username/project.git". If you added an SSH key to github and have it running on ssh-agent locally, then you should be able to push without entering a username or password.

O
OLIVER.KOO

Add Identity without Keychain

There may be times in which you don't want the passphrase stored in the keychain, but don't want to have to enter the passphrase over and over again.

You can do that like this:

ssh-add ~/.ssh/id_rsa 

This will ask you for the passphrase, enter it and it will not ask again until you restart.

Add Identity Using Keychain

As @dennis points out in the comments, to persist the passphrase through restarts by storing it in your keychain, you can use the --apple-use-keychain option (-k for Ubuntu) when adding the identity like this:

ssh-add --apple-use-keychain ~/.ssh/id_rsa

Once again, this will ask you for the passphrase, enter it and this time it will never ask again for this identity.


Note that this won't persist the identity on restarts. You can use the -K option to store the passphrase in your keychain when adding it, e.g. ssh-add -K ~/.ssh/id_rsa
lower case -k for me... (Linux Mint / Ubuntu 14.04 base) but yes! finally sorted this...
just running the command "ssh-add" and enter the password once, command line will not prompt you for the password again.
You don't need any arguments; just running ssh-add will automatically add ~/.ssh/id_rsa (among other files). And there's no reason to send the output to /dev/null; much better to see the report of what it did.
Any idea why I get "Could not open a connection to your authentication agent."?
S
Simon Boudrias

If you work with HTTPs urls, it'll always ask for your username / password.

If you're correctly using SSH when cloning / setting remotes. Then make sure you have a ssh-agent to remember your password. That way, you'll only enter your passphrase once by terminal session.

If it is still too annoying, then simply set a ssh-key without passphrase.


thanks for the response. I've always just used HTTPs. I am trying to achieve SSH authentication and thought I set it up. Is the ssh-agent something outside of git I need to install? Thanks
I just want to note that passphrases are used to encrypt your private key, so if you don't use a passphrase, then your private key will be unencrypted on your machine. It's like leaving a password in a text file laying around on your computer.
Funny, my HTTPS repos never ask for passwords and my SSH repos always do.
See this github doc to convert remote's URL from https to ssh. To check if remote's URL is ssh or https, use git remote -v. To switch from https to ssh: git remote set-url origin git@github.com:USERNAME/REPOSITORY.git
Downvoted because the "what" should include a "how".
G
Groot

On Mac OSX you can add your private key to the keychain using the command:

ssh-add -K /path/to/private_key

If your private key is stored at ~/.ssh and is named id_rsa:

ssh-add -K ~/.ssh/id_rsa

You will then be prompted for your password, which will be stored in your keychain.

Edit - Handle restart

In order to not have to fill in your password even after a restart add the following to your ssh configuration file (commonly located at ~/.ssh/config)

Host *
  UseKeychain yes
  AddKeysToAgent yes
  IdentityFile ~/.ssh/id_rsa

In my case, it's still prompting for the passphrase after restart (macOS Sierrra 10.12.2). Any ideas on how to solve this?
Nevermind, I've just found the issue. It's a bug (feature?) from Mac OS X 10.12 in which the ssh-agent does not automatically load passphrases on the keychain during startup. github.com/lionheart/openradar-mirror/issues/15361
@Groot, BTW, adding "Host * UseKeychain yes" to "~/.ssh/config", as suggested in other answers, fixes the issue.
This should be the accepted answer. Specially the config file in ~/.ssh
I kept getting prompts to "Enter passphrase for key .ssh/id_rsa:" - ssh-add -K ~/.ssh/id_rsa resolved this
C
ChrisJF

I tried all the answers here and none of these answers worked! My password would not persist between sessions/restarts of my Mac.

What I found out from reading this OpenRadar and this Twitter discussion was that Apple purposely changed the behaviour for ssh-agent in macOS 10.12 Sierra to no longer automatically load the previous SSH keys. In order to maintain the same behaviour as El Cap I did the following:

ssh-add -K ~/.ssh/id_rsa Note: change the path to where your id_rsa key is located. ssh-add -A Create (or edit if it exists) the following ~/.ssh/config file: Host * UseKeychain yes AddKeysToAgent yes IdentityFile ~/.ssh/id_rsa

And now my password is remembered between restarts of my Mac!


This might be something useful to add to either the github or osx documentation pages. Had the hardest time figuring out why my Mac running 10.11 and my other running 10.12 where behaving differently.
Happened to me after an OSX upgrade, thanks (I think ssh-add -A is not needed if you have only one key at ~/.ssh/id_rsa)
I just upgraded to macOS 10.12 and this was super useful. Thanks!
As of October 2017, this answer is exactly what you're looking for if you are using macOS 10.12 or higher.
And this is now on the github docs: help.github.com/articles/…
J
Junaid

TL;DR You need to use an ssh agent. To do that, open terminal & before pushing to git, execute ssh-add enter your passphrase when prompted.

Check out the original StackExchange answer here


This works, but what happens is that you have to repeat this command each time you boot your computer.
@WilliamGrand this hasn't been the case for me though but if you're saying then, of course, I believe you :]. I'll see if I can find anything & I'll update the answer accordingly.
s
sudo bangbang

You can remove passphrase for the key

$ ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]

or you can run

$ ssh-keygen -p

you get a prompt for keyfile. By default it ~/.ssh/id_rsa so press enter

You'll be prompted for current pass phrase enter it.

Then there will be a prompt for new pass phrase, press enter


This should be higher than a lot of the nearly identical answers for adding the passphrase to the keychain. I had to give my public key to an administrator, and included a passphrase which became annoying to type every time. This is a clean solution when you don't have much control over your machine (-K, -k, -A did not work for me).
This is the only thing that worked for me across restarts, all the ssh-add -K, -k, etc. commands didn't do a thing for me.
It works perfectly for me too, I used the first approach ssh-keygen -p -P MyOldPassPhrase -N "" -f ~/.ssh/mykeyfile. Thanks!
This is the answer.
M
Mahtab Alam

Make sure you are using ssh for your repository also

mahtab@mahtab-Lenovo-G50-70:~/my-projects/jenkins-cje-2017$ git remote -v origin git@github.com:eMahtab/jenkins-cje-2017.git (fetch) origin git@github.com:eMahtab/jenkins-cje-2017.git (push)

https://i.stack.imgur.com/LVnVW.png

Don't use https, if your remote is using https then it will keep asking for password, even If you have added the public key to Github and added private key to ssh-agent. Below will always ask for password

mahtab@mahtab-Lenovo-G50-70:~/my-projects/jenkins-cje-2017$ git remote -v origin https://github.com/eMahtab/jenkins-cje-2017.git (fetch) origin https://github.com/eMahtab/jenkins-cje-2017.git (push)


Yes differentiating between the two remote URL types was helpful for me. This helped me in terms of git pull and git push. I switched my url from HTTPS type to SSH type, and it worked--git pull stopped asking for password.
Switching can be done with this command: git remote set-url origin git@github.com:USERNAME/REPOSITORY.git
S
Syden

Just run the following command:

ssh-add -K

It will never ask you to enter the password again.


This works great, but I was a little concerned about running a random command. However, if you check the docs ssh-add just "adds private key identities to the authentication agent", and the -K option simply makes it so "When adding identities, each passphrase will also be stored in the user's keychain."
Actually, it only fixed it until I restarted :(
in the bash shell for Windows, the "-k" flag has to be lowercase. Just FYI
The option -K is not available on prior versions of ssh-add. This is why it is not working for many. The option -k (lower case) IS NOT the same and you will have to re-type your passphrase next time you open a session.
B
Black

I had to execute:

eval `ssh-agent -s`
ssh-add

Note: You will have to do this again after every restart. If you want to avoid it, then enter it in your ".bashrc" file which is in C:\Users\<<USERNAME>>\.bashrc on windows. It is probably hidden, so make sure that you can see hidden files.

Solution found here.


L
Lee Goddard

If you're using windows, this worked for me:

eval `ssh-agent -s`
ssh-add ~/.ssh/*_rsa

It'll ask for passphrase in the second command, and that's it.

Add these lines to your bash profile, $HOME/.bash_profile or $HOME/.bashrc.


When you logout and relog you have to re-enter the password each time.
C
CM777

This page on github has the answer you need. You have to switch to ssh authentication from https.

Check how it is authenticating as follows.

$ git remote -v
> origin  https://github.com/USERNAME/REPOSITORY.git (fetch)
> origin  https://github.com/USERNAME/REPOSITORY.git (push)

Change your remote's URL from HTTPS to SSH with the git remote set-url command.

$ git remote set-url origin git@github.com:USERNAME/REPOSITORY.git

Test it again with

$ git remote -v
# Verify new remote URL
> origin  git@github.com:USERNAME/REPOSITORY.git (fetch)
> origin  git@github.com:USERNAME/REPOSITORY.git (push)

That's all. It will work now.


This answer works if you the remote repo url is changed from https to ssh. Thanks.
p
possumkeys

Use ssh-add command to add your public key to the ssh-agent.

ssh-add

Make sure the ssh public key e.g. ~/.ssh/id_rsa.pub is what you have in your repo settings.

Make sure you can actually ssh into the server e.g. For Bitbucket:

ssh -T git@bitbucket.org

Update the url to move from https to ssh. You can check which you use by checking the output of:

git remote -v

If you see a https:// in the urls, then you are still using https. To update it: Take the url and just replace https:// with ssh:// e.g. Change:

https://git@bitbucket.org/../..

To:

ssh://git@bitbucket.org/../..

Referenced: https://docs.github.com/en/github/using-git/changing-a-remotes-url#switching-remote-urls-from-https-to-ssh


Д
ДМИТРИЙ МАЛИКОВ
B
Brad

This is what worked for me:

git config --global core.sshCommand "'C:\Windows\System32\OpenSSH\ssh.exe'"

Thanks, didn't think about that, I use windows ssh with the config to access my servers via ssh, and it works with keys and stores passphrase seamlessly, never thought I can do that for git too. Thanks!
z
zedd45

For Mac OSX Sierra, I found that the fixes suggested in the github issue for Open Radar fixed my problem. Seems like Sierra changed the default behavior (I started having this problem after upgrading).

This one I found especially useful: https://github.com/lionheart/openradar-mirror/issues/15361#issuecomment-249059061

ssh-add -A 

This resulted in my identity being added to the agent, after I ran

ssh-add -K {/path/to/key}

To summarize, in OSX.12:

ssh-add -K {/path/to/key}
ssh-add -A 

should result in:

Identity added: {/path/to/file} ({/path/to/file})

EDIT: I noticed the next time I did a full reboot (aka the agent stopped and restarted) this no longer worked. The more complete solution is what @ChrisJF mentioned above: creating a ~/.ssh/config file. Here's the output of mine:

$ cat ~/.ssh/config
Host *
  UseKeychain yes
  AddKeysToAgent yes
  IdentityFile ~/.ssh/id_rsa

You can add as many IdentityFile entries as you need, but this is the default setup. This is the "trending" answer on the openradar link above, ATM, as well.


The edited one solved my issue. MacOS Mojave 10.14.3
D
DhineshYes

Worked in LinuxMint/Ubuntu

Do the following steps

Step 1:

Goto file => /.ssh/config

Save the below lines into the file

Host bitbucket.org
    HostName bitbucket.org
    User git
    IdentityFile /home/apple/myssh-privatekey
    AddKeysToAgent yes

Don't forget to add this line AddKeysToAgent yes

Step 2:

Open the terminal and add the keyset to the ssh-add

$ ssh-add -k /home/apple/myssh-privatekey

provide the passphrase.


a
aboutaaron

I recently upgraded to macOS Mojave, and installed some tools via homebrew, which seemed to swap Apple's version of ssh-add for the different one. My default version of ssh-add did not have the -K option. This led to the following error:

# ssh-add: illegal option -- K

You can see which version of ssh-add you have by running which ssh-add.

(Mine was stored in /usr/local/bin/ssh-add)

To fix this, I had to point the key to Apple's version:

/usr/bin/ssh-add -K ~/.ssh/id_rsa

Git/GitHub worked perfectly afterward. For more information, see: Error: ssh-add: illegal option -- K


Had the same problem on my iMac with High Sierra 10.13.6 - this worked for me. Thanks!
Mine had been working fine & randomly started asking for passphrases again - might've been after a recent update. This fixed it! Thanks
c
chaosifier

This answer is primarily for windows users and also equally relevant if you're having trouble cloning with tfs, github or gitlab on any other OS.

The default authentication mode when using SSH is the private key. Whenever that fails for some reason, the ssh-agent falls back to username and password based authentication.

There are several reasons why the default key based authentication might have failed. Following are the most common cases :

a) The ssh-agent cannot find the default private key file which is id_rsa, and no other key path is specified explicitly.

b) The public key stored in the server is incorrect.

c) The path you're trying to clone is incorrect.

In any case, to troubleshoot the issue, first of all execute the git clone command with verbose logging with the command :

GIT_TRACE=1 GIT_SSH_COMMAND="ssh -vvv" git clone ssh://pathToYourRepo

You can go through each step in the log to get an intuition of what the issue might be.

Troubleshooting in case of (a)

Make sure you have the default key name id_rsa in the .ssh directory. You might have specified some different keyname when generating the key with ssh-keygen command or maybe there isn't any key at all).

In case you want to specify a different key for authentication, use the following command : ssh-agent bash -c 'ssh-add ~/.ssh/anotherKey; git clone ssh://pathToYourRepo'

Troubleshooting in case of (b)

Make sure there aren't extra white spaces when storing the public key in the server.

Troubleshooting in case of (c)

Make sure you aren't trying to clone with the https version of the repository path.


..."Make sure you aren't trying to clone with the https version of the repository path"... OH... thank you!!!
J
James Bond

If you used for your GIT the password authentication before, but now are using SSH authentication, you need to switch remote URLs from HTTPS to SSH:

git remote set-url origin git@github.com:USERNAME/REPOSITORY.git

A
André Herculano

I already had set a passphrase but for some reason it wouldn't recognize it anymore. So I just added the identity file to my keychain again using ssh-add -K and it stopped asking for my password.


this only loads keys and not certificates
y
yebowhatsay

Adding to the above answers. Had to do one more step on Windows for git to be able to use ssh-agent.

Had to run the following command in powershell to update the environment variable:

PS> [Environment]::SetEnvironmentVariable("GIT_SSH", "$((Get-Command ssh).Source)", [System.EnvironmentVariableTarget]::User)

Restart VSCode, Powershell or whatever terminal you are using to activate the env variable.

Complete instructions can be found [here] (https://snowdrift.tech/cli/ssh/git/tutorials/2019/01/31/using-ssh-agent-git-windows.html).


B
Bryan Perez

Problem seems to be because you're cloning from HTTPS and not SSH. I tried all the other solutions here but was still experiencing problems. This did it for me.

Using the osxkeychain helper like so:

Find out if you have it installed. git credential-osxkeychain If it's not installed, you'll be prompted to download it as part of Xcode Command Line Tools. If it is installed, tell Git to use osxkeychain helper using the global credential.helper config: git config --global credential.helper osxkeychain

The next time you clone an HTTPS url, you'll be prompted for the username/password, and to grant access to the OSX keychain. After you do this the first time, it should be saved in your keychain and you won't have to type it in again.


A
Anang Satria

Generally, here are the steps to allow you make a remote connection to your server using ssh without password:

Create a pair of rsa private and public key $ ssh-keygen -t rsa -b 4096 -C "your comments"

Copy your public key and login to your remote server

Add your public key to .ssh/authorized_keys

If you have multiple ssh keys in your computer you might to add your key using ssh-add $ ssh-add /path/to/private/key

Then try ssh to your server $ ssh username@your_ip_address

Source: http://diary-of-programmer.blogspot.com/2018/08/tips-how-to-ssh-to-your-digitalocean.html


P
PavDub

SSH Key - Still asking for password and passphrase

If on Windows and using PuTTY as the SSH key generator, this quick & easy solution turned out to be the only working solution for me using a plain windows command line:

Your PuTTY installation should come with several executable, among others, pageant.exe and plink.exe When generating a SSH key with PuttyGen, the key is stored with the .ppk extension Run "full\path\to\your\pageant.exe" "full\path\to\your\key.ppk" (must be quoted). This will execute the pageant service and register your key (after entering the password). Set environment variable GIT_SSH=full\path\to\plink.exe (must not be quoted). This will redirect git ssh-communication-related commands to plink that will use the pageantservice for authentication without asking for the password again.

Done!

Note1: This documentation warns about some peculiarities when working with the GIT_SHH environment variable settings. I can push, pull, fetch with any number of additional parameters to the command and everything works just fine for me (without any need to write an extra script as suggested therein).

Note2: Path to PuTTY instalation is usually in PATH so may be omitted. Anyway, I prefer specifying the full paths.

Automation:

The following batch file can be run before using git from command line. It illustrates the usage of the settings:

git-init.bat
   @ECHO OFF
   :: Use start since the call is blocking
   START "%ProgramFiles%\PuTTY\pageant.exe" "%HOMEDRIVE%%HOMEPATH%\.ssh\id_ed00000.ppk"
   SET GIT_SSH=%ProgramFiles%\PuTTY\plink.exe

Anyway, I have the GIT_SSH variable set in SystemPropertiesAdvanced.exe > Environment variables and the pageant.exe added as the Run registry key (*).

(*) Steps to add a Run registry key>

run regedit.exe Navigate to HKEY_CURRENT_USER > Software > Microsoft > Windows > CurrentVersion > Run Do (menu) Edit > New > String Value Enter an arbitrary (but unique) name Do (menu) Edit > Modify... (or double-click) Enter the quotes-enclosed path to pageant.exe and public key, e.g., "C:\Program Files\PuTTY\pageant.exe" "C:\Users\username\.ssh\id_ed00000.ppk" (notice that %ProgramFiles% etc. variables do not work in here unless choosing Expandable string value in place of the String value in step 3.).


V
Vinayak Deshpande

If you are using ssh url for git, when prompted for password for ssh put the username as "git" and the password as your system's login password


Changing repository remote URL type from HTTPS to SSH solved my issue. Thanks @MichaelR, your article was really helpful, though I haven't read anything from it :D
L
Lost Koder

Use ssh remote url provided by Github not https.


The OP clearly said he's using SSH instead of HTTPS.
L
Lerner Zhang

I'd like to add an answer for those who may still need to enter the password because they have set IdentitiesOnly as yes. This may cause by multiple keys and the identity file, being keys for git or server.

After I have generated the key and copied it to the server:

ssh-keygen
ssh-copy-id -i ~/.ssh/12gpu_server.pub lerner@192.168.20.160

I found it didn't work.

Then I went to check the ~/.ssh/config file, I saw this at the bottom:

Host *
IdentitiesOnly yes

Then I add this above:

Host 12gpu
HostName 192.168.20.160
User lerner
IdentityFile ~/.ssh/12gpu_server

I can just log in by entering ssh 12gpu.

Then you can add multiple ssh keys using your favorite names, and you only need to add the settings like the above four lines to the config file.

Host is the name you'd like to enter when you connect to the server later; the HostName is the server's ip or domain like github.com; User is the user name you log in the server like the user name or git for github or gitlab; and the IdentityFile is the file where you store the key you have generated.


F
Fabian Stern

If you are using Windows and GIT without third party tools and your key is not secured by a password / passphrase use this:

Environment Variable HOME must be set to your user profile (e.g. C:\Users\Laptop) Go to C:\Users\Laptop\.ssh\ folder and edit "config" file (or create the file!) Example: C:\Users\Laptop.ssh\config (note: there is no . at the end!) Add your git-server host to the "config" file like so: #Example host entry Host myhostname.com HostName myhostname.com User git IdentityFile c:/users/laptop/.ssh/id_rsa.pub PasswordAuthentication no Port 422 Save the file and clone the repository like this: git clone ssh://myhostname.com/git-server/repos/picalc.git

You can use additional configuration parameters for the "config" file host entry. These can be found in your local git installation folder, e.g. "C:\Program Files\Git\etc\ssh\ssh_config". Excerpt:

# Host *
#   ForwardAgent no
#   ForwardX11 no
#   RhostsRSAAuthentication no
#   RSAAuthentication yes
#   PasswordAuthentication yes
#   HostbasedAuthentication no
#   GSSAPIAuthentication no
#   GSSAPIDelegateCredentials no
#   BatchMode no
#   CheckHostIP yes
#   AddressFamily any
#   ConnectTimeout 0
#   StrictHostKeyChecking ask
#   IdentityFile ~/.ssh/identity
#   IdentityFile ~/.ssh/id_rsa
#   IdentityFile ~/.ssh/id_dsa
#   IdentityFile ~/.ssh/id_ecdsa
#   IdentityFile ~/.ssh/id_ed25519
#   Port 22
#   Protocol 2
#   Cipher 3des
#   Ciphers aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc
#   MACs hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160
#   EscapeChar ~
#   Tunnel no
#   TunnelDevice any:any
#   PermitLocalCommand no
#   VisualHostKey no
#   ProxyCommand ssh -q -W %h:%p gateway.example.com
#   RekeyLimit 1G 1h

B
Bruno Leite

Same problem to me and the solution was:

See this github doc to convert remote's URL from https to ssh. To check if remote's URL is ssh or https, use git remote -v. To switch from https to ssh: git remote set-url origin git@github.com:USERNAME/REPOSITORY.git @jeeYem


A
Amir Heshmati

Mobaxterme had a UI interface for it

setting > configuration > SSH > SSH Agent > [check] Use internal SSH agent "moboAgent" > add [your id_rsa and restart mobaxterme to set changes]