How to specify the private SSH-key to use when executing shell command on Git?
Asked Answered
A

41

1801

A rather unusual situation perhaps, but I want to specify a private SSH-key to use when executing a shell (git) command from the local computer.

Basically like this:

git clone [email protected]:TheUser/TheProject.git -key "/home/christoffer/ssh_keys/theuser"

Or even better (in Ruby):

with_key("/home/christoffer/ssh_keys/theuser") do
  sh("git clone [email protected]:TheUser/TheProject.git")
end

I have seen examples of connecting to a remote server with Net::SSH that uses a specified private key, but this is a local command. Is it possible?

Ay answered 30/12, 2010 at 19:42 Comment(7)
See this question in SuperUser as well.Octosyllabic
I'm wondering why this is so unusual that Git doesn't have an -i option like ssh does.Urethra
With git 2.10 (Q3 2016), you also have a new config: git config core.sshCommand 'ssh -i private_key_file'. See my answer belowScaremonger
Is it really for one-time use ? If not one should associate host aliases and keys in ~/.ssh/config first. Details hereBarehanded
gist.github.com/Tamal/1cc77f88ef3e900aeae65f0e5e504794 here you can find a script with the solutionGlossology
This is documented already: git-scm.com/docs/gitfaq#Documentation/…Kurdish
I had to purge everything from my ssh agent before it would work because for some reason it kept picking up the old one no matter what. A reboot may also fix this I guess.Slavophile
N
1132

Something like this should work (suggested by orip):

ssh-agent bash -c 'ssh-add /somewhere/yourkey; git clone [email protected]:user/project.git'

if you prefer subshells, you could try the following (though it is more fragile):

ssh-agent $(ssh-add /somewhere/yourkey; git clone [email protected]:user/project.git)

Git will invoke SSH which will find its agent by environment variable; this will, in turn, have the key loaded.

Alternatively, setting HOME may also do the trick, provided you are willing to setup a directory that contains only a .ssh directory as HOME; this may either contain an identity.pub, or a config file setting IdentityFile.

Nikianikita answered 30/12, 2010 at 19:48 Comment(14)
But this will add the key permanently as an accepted SSH-key, right? I want to avoid that so that theuser2 can't mess with theuser's projects. It's for a web application so it's not practical to use different OS-users, which would have been the best option.Ay
No, when git completes, ssh-agent terminates, and the key is forgotten.Eveevection
this command does'not work on windows git bash. It says syntax error near unexpected token 'ssh-add'Cutpurse
Fixed command line (for windows or linux) would be something like: ssh-agent bash -c 'ssh-add sshkey; git clone url'Interested
This works fine on my desktop *nix machines, but fails on several servers that are virgin installs of current Debian. @HeyWatchThis's answer seems to work everywhere (although it's permanent where this one is temporary)Guam
bash crashes on windows for me (using git bash environment variables). Is there a workaround for windows.Augury
I've fixed the syntax of the first command line: it should be $( ... ) to launch a subshell.Pacer
The ssh-agent $(..) syntax isn't working for me and I'm not sure how this is suppose to work: (ba)sh should execute the commands inside $(..) first, then run ssh-agent with the output as parameter.Distribute
Unfortunately instead of removing the key, it left it there. You should add a ssh-add -d /path/to/key at the end.Microbe
The $(..) syntax probably doesn't do what you expect: it runs the commands inside first and sends their output to ssh-agent. This might happen to work anyway if another ssh-agent happens to be already running, but then the new key will be left in the agent (unless you add ssh-add -d to take it out) and the answer becomes ssh-add /somewhere/yourkey && git clone [email protected]:user/project.git ; ssh-add -d /somewhere/yourkey (and we assume ssh-agent is already running, and note the use of && rather than ;). But that's moot because the bash -c version is correct.Lianeliang
This solution stopped working for me for some reason after I upgraded from OpenSUSE 42.3 to 15.0. I switched to https://mcmap.net/q/14116/-how-to-specify-the-private-ssh-key-to-use-when-executing-shell-command-on-git, which is working well.Exosmosis
You also accomplish this with ssh-add -t 60; git clone [email protected]:user/project.git. That will just expire the key after 60 seconds.Almonry
This worked for me on Windows 10 for quite some time, but in the past week it's stopped working and I can't seem to pinpoint the change. Infact it fails to work on two separate systems. The ssh-agent service despite running, reports nothing though running with -d generates a cannot create agent root reg key, ERROR:5 error.Instal
And then do git config core.sshCommand "ssh -i /path/to/key" so that it remembers your key every time you do a git fetch / git pullMineralogist
T
1674

None of these solutions worked for me.

Instead, I elaborate on @Martin v. Löwis 's mention of setting a config file for SSH.

SSH will look for the user's ~/.ssh/config file. I have mine setup as:

Host gitserv
    Hostname remote.server.com
    IdentityFile ~/.ssh/id_rsa.github
    IdentitiesOnly yes # see NOTES below
    AddKeysToAgent yes

And I add a remote git repository:

git remote add origin git@gitserv:myrepo.git

(or clone a fresh copy of the repo with git@gitserv:myrepo.git as address)

And then git commands work normally for me.

git push -v origin master

If you have submodules, you can also execute the following in the repo directory, to force the submodules to use the same key:

git config url.git@gitserv:.insteadOf https://remote.server.com

NOTES

  • The IdentitiesOnly yes is required to prevent the SSH default behavior of sending the identity file matching the default filename for each protocol. If you have a file named ~/.ssh/id_rsa that will get tried BEFORE your ~/.ssh/id_rsa.github without this option.

  • AddKeysToAgent yes lets you avoid reentering the key passphrase every time.

  • You can also add User git to avoid writing git@ every time.

References

Terrence answered 28/6, 2012 at 19:44 Comment(17)
I found that when you specify multiple keys using .ssh/config, you need to use host friend name in line "Host" as part of "git remote add" command. If line is "Host stg", then you need to use git remote add <someName> user@stg:/path_to_git_repo.git ". If you use exact server name like [email protected]:/path_to_git_repo.git, the config file is not picked by git. Hence, it is not picking private key file correctly. I tried this by pushing same content to github and heroku and works only when you give friendly name in "git remote add"Collateral
I wasn't sure about the Host for github. I found this link: gist.github.com/jexchan/2351996.Ionone
@JonnyReeves edits introduced mismatched hostnames. Pushing to gitserv will not match the ssh config Host entry for remote or remote.server.com. Therefore the intended IdentityFile will not be used. I'm going to edit this answer.Amundson
Take a look here if you want to have few key files for few git repositoriesLankester
I don't understand why IdentitiesOnly is necessary. As I understand it, by adding this host to the config file, it will add this ssh key to a list of keys that it will try, i.e. it will first try ~/.ssh/identity, ~/.ssh/id_dsa, ~/.ssh/id_ecdsa and ~/.ssh/id_rsa and then it will try ~/.ssh/id_rsa.github. Is there anything wrong with it trying id_rsa before id_rsa.github, as long as it eventually tries id_rsa.github?Simmer
Umm this doesn't work for me. When I do a git pull from my private repo, git ignores my .ssh/config file completely and tries id_rsa instead, which is the wrong key.Essequibo
I had all of this except for IdentitiesOnly and it worked for a while but then one day stopped working and was trying to use my default key in id_rsa. IdentifiesOnly does seem to be important.Stem
You could use Host remote.server.com and keep using the original URLCereus
For some reason, this worked for me, but I add to SSH-login to the Git server first for the identifyFile to be used (Probably has to do with the known_hosts not being populated). So, after doing that, and before running your git clone ... command, run: ssh {hostname}Flower
Also User may be required in the config entryCompute
This worked for me after two changes. If the config file is new, don't forget to do chmod 600 ~/.ssh/config (see here). And if you are using GitHub, replace Host gitserv with Host github.com, omit Hostname remote.server.com, and add remote with git remote add origin [email protected]:user_name/repo_name.git.Launceston
To save some more characters, add User git into that configuration item and just use gitserv:myrepo.git as remote URL.Gymnasiarch
This is the only answer that also works with Windows if you are using the ssh client that comes with Git (located at %ProgramFiles%\Git\usr\bin\ssh.exe by default). Modify or create the config file located at %USERPROFILE%\.ssh\config.Radiophotograph
I needed to use Host instead of Hostname. I.e. Host xfce.org\nHost gitlab.xfce.orgRosenarosenbaum
github: HostName github.com User git (answered by Karsten), gitlab: HostName gitlab.com User gitLamentable
it looks like the comment makes it fail: /root/.ssh/config line 4: garbage at end of line; "#". so if this is the case, remove the commentKlinges
I've took liberty to add a solution for submodules.Diversity
N
1132

Something like this should work (suggested by orip):

ssh-agent bash -c 'ssh-add /somewhere/yourkey; git clone [email protected]:user/project.git'

if you prefer subshells, you could try the following (though it is more fragile):

ssh-agent $(ssh-add /somewhere/yourkey; git clone [email protected]:user/project.git)

Git will invoke SSH which will find its agent by environment variable; this will, in turn, have the key loaded.

Alternatively, setting HOME may also do the trick, provided you are willing to setup a directory that contains only a .ssh directory as HOME; this may either contain an identity.pub, or a config file setting IdentityFile.

Nikianikita answered 30/12, 2010 at 19:48 Comment(14)
But this will add the key permanently as an accepted SSH-key, right? I want to avoid that so that theuser2 can't mess with theuser's projects. It's for a web application so it's not practical to use different OS-users, which would have been the best option.Ay
No, when git completes, ssh-agent terminates, and the key is forgotten.Eveevection
this command does'not work on windows git bash. It says syntax error near unexpected token 'ssh-add'Cutpurse
Fixed command line (for windows or linux) would be something like: ssh-agent bash -c 'ssh-add sshkey; git clone url'Interested
This works fine on my desktop *nix machines, but fails on several servers that are virgin installs of current Debian. @HeyWatchThis's answer seems to work everywhere (although it's permanent where this one is temporary)Guam
bash crashes on windows for me (using git bash environment variables). Is there a workaround for windows.Augury
I've fixed the syntax of the first command line: it should be $( ... ) to launch a subshell.Pacer
The ssh-agent $(..) syntax isn't working for me and I'm not sure how this is suppose to work: (ba)sh should execute the commands inside $(..) first, then run ssh-agent with the output as parameter.Distribute
Unfortunately instead of removing the key, it left it there. You should add a ssh-add -d /path/to/key at the end.Microbe
The $(..) syntax probably doesn't do what you expect: it runs the commands inside first and sends their output to ssh-agent. This might happen to work anyway if another ssh-agent happens to be already running, but then the new key will be left in the agent (unless you add ssh-add -d to take it out) and the answer becomes ssh-add /somewhere/yourkey && git clone [email protected]:user/project.git ; ssh-add -d /somewhere/yourkey (and we assume ssh-agent is already running, and note the use of && rather than ;). But that's moot because the bash -c version is correct.Lianeliang
This solution stopped working for me for some reason after I upgraded from OpenSUSE 42.3 to 15.0. I switched to https://mcmap.net/q/14116/-how-to-specify-the-private-ssh-key-to-use-when-executing-shell-command-on-git, which is working well.Exosmosis
You also accomplish this with ssh-add -t 60; git clone [email protected]:user/project.git. That will just expire the key after 60 seconds.Almonry
This worked for me on Windows 10 for quite some time, but in the past week it's stopped working and I can't seem to pinpoint the change. Infact it fails to work on two separate systems. The ssh-agent service despite running, reports nothing though running with -d generates a cannot create agent root reg key, ERROR:5 error.Instal
And then do git config core.sshCommand "ssh -i /path/to/key" so that it remembers your key every time you do a git fetch / git pullMineralogist
N
910

Starting from Git 2.3.0 we also have the simple command (no config file needed):

GIT_SSH_COMMAND='ssh -i private_key_file -o IdentitiesOnly=yes' git clone user@host:repo.git

Note the -o IdentitiesOnly=yes is required to prevent the SSH default behavior of sending the identity file matching the default filename for each protocol as noted in the answer above.

Noble answered 20/4, 2015 at 17:3 Comment(14)
I get cannot run ssh -i /home/vagrant/.ssh/git: No such file or directory though it exists 444 Nov 16 18:12 /home/vagrant/.ssh/git from ls -l /home/vagrant/.ssh/gitForeshank
@ted: chmod 400 /home/vagrant/.ssh/gitAlverson
Nice and easy solution. I suggest creating an alias if you need to do this a lot.Hidalgo
@Foreshank Read What permissions levels should I give to the private key? if confused.Vista
Don't forget to chmod 400 <path-to-private-key-file>. Otherwise git command may fail with no special error message...Formative
This worked for me using Git 2.13.6 on Mac. I was able to clone a remote repo over a SSH forward proxy. Thanks! Note: I only had to export GIT_SSH_COMMAND='ssh -i private_key_file' though.Duffie
Please note that also .ssh folder has to be granted permissions, besides the subfolder as mentioned above... so be sure to run chmod 400 path/to/.ssh too...Cavendish
It would be good if this answer also included -o IdentitiesOnly=yes to make sure that the key specified with -i gets used (as opposed to a key from SSH agent).Aegina
To do this from within PowerShell: $env:GIT_SSH_COMMAND='ssh -i private_key_file -o IdentitiesOnly=yes'; git clone user@host:repo.gitInstal
Yea alias is nice, alias GIT="GIT_SSH_COMMAND='ssh -i private_key_file -o IdentitiesOnly=yes' git", and then e.g. GIT pushFarris
If you have identities specified in your ~/.ssh/config file that you want to ignore, you will also need to add -F /dev/null to the ssh command.Insolent
For those looking for a per repo config, you can add this to the core.sshCommand config option for your repo. Note that the path to the identity file should resolve from the repo as your directory, so typically it should be something like ~/.ssh/identity_file.Laurettelauri
If you're on Windows WSL you might need a sudo if permissions are too open, so like this: sudo GIT_SSH_COMMAND='ssh -i /mnt/c/Users/dome/path/to/mykey -o IdentitiesOnly=yes' git push [email protected]:do-me/SemanticFinder.git.Consols
This one works well when you have multiple ssh binaries, and the ssh-agent loaded into memory is using the wrong binary you need. (FIPS requirements etc.)The
L
538

Other people's suggestions about ~/.ssh/config are extra complicated. It can be as simple as:

Host github.com
  IdentityFile ~/.ssh/github_rsa
Layamon answered 17/9, 2013 at 0:39 Comment(8)
You need the IdentitiesOnly option, too.Octosyllabic
@EnzeChi you can have multiple github accounts by manipulating the remotes: git remote add ssh://personal/org/proj.git && git remote add ssh://corporate/org/proj.git. Then you config looks like Host personal HostName github.com ... Host corporate HostName github.comOre
Mine works without the IdentitiesOnly option. Can someone explain why this should be required?Coretta
Not exactly fitting granularity. My company has an organisation on github and I have a personal account on github, so with just the host it does not work nicely.Peking
Is there a difference between Host *.github.com and Host github.com?Sigmon
@Peking you can make custom hosts: Host mypersonalgithub // HostName github.com // IdentityFIle personalgithub_ed25519 and Host companygithub // HostName github.com // IdentityFIle company_ed25519Sigmon
@Coretta it likely works because the host doesn't care how many keys you try. Some hosts reject the connection after a certain number of failed keys.Undo
@Sigmon I have not had issues with *.github.com until today after months of it working fine. I did add more entries in my config file but should have been unrelated. After removing the *. it started working immediatelyCountry
S
397

With git 2.10+ (Q3 2016: released Sept. 2d, 2016), you have the possibility to set a config for GIT_SSH_COMMAND (and not just an environment variable as described in Rober Jack Will's answer)

See commit 3c8ede3 (26 Jun 2016) by Nguyễn Thái Ngọc Duy (pclouds).
(Merged by Junio C Hamano -- gitster -- in commit dc21164, 19 Jul 2016)

A new configuration variable core.sshCommand has been added to specify what value for GIT_SSH_COMMAND to use per repository.

core.sshCommand:

If this variable is set, git fetch and git push will use the specified command instead of ssh when they need to connect to a remote system.
The command is in the same form as the GIT_SSH_COMMAND environment variable and is overridden when the environment variable is set.

It means the git pull can be:

cd /path/to/my/repo/already/cloned
git config core.sshCommand 'ssh -i private_key_file' 
# later on
git pull

When cloning a new repo, where there is not yet any .git/config to modify, can first set it for just one command like git clone or git submodule add:

git -c core.sshCommand="ssh -i private_key_file" clone host:repo.git

Once the repo exists you can set the option permanently in the .git/config:

cd <repo or submodule you just cloned>
git config core.sshCommand "ssh -i private_key_file"

This is easier than setting a GIT_SSH_COMMAND environment variable, which, on Windows, as noted by Mátyás Kuti-Kreszács, would be

set "GIT_SSH_COMMAND=ssh -i private_key_file"

For all those commands, you can add a -o IdentitiesOnly=yes to limit SSH to the the private/public key you are specifying:

git config core.sshCommand 'ssh -i private_key_file -o IdentitiesOnly=yes' 
# or
git -c core.sshCommand="ssh -i private_key_file -o IdentitiesOnly=yes" clone host:repo.git
# or
set "GIT_SSH_COMMAND=ssh -i private_key_file -o IdentitiesOnly=yes"

gsullins suggests in the comments to adds to the .zshrc the following alias:

alias git.key1="git config core.sshCommand 'ssh -i <absolute path to private key>'"

As noted by Jaredo Mills in a comment:

One pitfall: if you mirror your repo to more than one host (Github, Gitlab), with different private keys, this method will send the wrong key.
The key is not associated with the repo, but with a username and hostname. ~/.ssh/config is the right place to get the association right, and it has the right matching capabilities for the job (see man ssh_config).

See HeyWatchThis's answer for illustration.

Scaremonger answered 20/7, 2016 at 6:47 Comment(6)
Works. Folks should consider this the best answer. Once issued, it can be informative to diff the .git/config file with a version copied to /tmp beforehand. A new entry has been created: sshCommand = ... For what it's worth, I used 'git config core.sshCommand "ssh -i $HOME/.ssh/privatekeyfile".Hairline
Only works with an existing git directory. Otherwise you need to set it globally which isn't really what you want.Zeniazenith
@Zeniazenith You can do the inline command git -c core.sshCommand="ssh -i private_key_file" clone host:repo.git followed by the config set git config core.sshCommand 'ssh -i private_key_file' Exaggerative
This works great thank you. Had to workaround another issue on Windows, if you are using the native Windows ssh and the Windows ssh-agent service you will need to specify the path to the windows ssh otherwise it will use the ssh shipped with git and you'll have to type the password in every time. git config core.sshCommand 'C:/Windows/System32/OpenSSH/ssh.exe -i C:/Users/firstname.lastname/.ssh/mygitkey_ed25519 -o IdentitiesOnly=yes' Bashan
@Bashan True. I always set the PATH to reference the ssh I want (C:\Program Files\Git\usr\bin\ssh.exe in my case). That way, no full path to specify.Scaremonger
@Johntron The -o IdentitiesOnly=yes is not mandatory but can help limit SSH to use only the specified private key instead of falling back to other possible authentication mechnism.Scaremonger
D
165

Contents of my_git_ssh_wrapper:

#!/bin/bash

ssh -i /path/to/ssh/secret/key $1 $2

Then you can use the key by doing:

GIT_SSH=my_git_ssh_wrapper git clone [email protected]:TheUser/TheProject.git
Dulse answered 17/2, 2012 at 1:32 Comment(5)
Nice solution. You can also simplify this with > GIT_SSH=my_git_ssh_wrapper; git clone [email protected]:TheUser/TheProject.gitAnagrammatize
This solution also covers situations when you want to use git from account without home directory.Exfoliation
Fantastic. You can use this way to private servers too: GIT_SSH="git_wrapper" git clone ssh://user@server/path/to/project"Knot
Don't forget to add executable permissions to script to avoid "Permission denied" errorHornswoggle
After cloning with this wrapper, you can set the wrapping command inside this particular project's git config cd projectname ; git config core.sshCommand 'ssh -i private_key_file -o IdentitiesOnly=yes' , and then you wont need to use wrapper for subsequent pullsJervis
E
160

To sum up answers and comments, the best way to set up git to use different key files and then forget about it, which also supports different users for the same host (e.g. a personal GitHub account and a work one), which works on Windows as well, is to edit ~/.ssh/config (or c:\Users\<your user>\.ssh\config) and specify multiple identities:

Host github.com
HostName github.com
IdentityFile /path/to/your/personal/github/private/key
User dandv

Host github-work
HostName github.com
IdentityFile /path/to/your/work/github/private/key
User workuser

Then, to clone a project as your personal user, just run the regular git clone command.

To clone the repo as the workuser, run git clone git@github-work:company/project.git.

Ecthyma answered 19/9, 2014 at 0:19 Comment(6)
I downvoted you because everything you say is already covered in the answers above, and in my eyes, even more clearly. For instance, why exactly do you define the User to e dandv and workuser, respectively?Golly
You answered a 4 year old question with no new informations and you are claiming that your answer is "the best way". Moreover you downvoted and hassled other users to remove their answer ... just to get your one pushed up.Icebound
@hroptatyr: I've used dandv and workuser to support my example, "e.g. a personal GitHub account and a work one". dandv is my GitHub username.Ecthyma
You've actually got the right idea here, but this won't work. You have to use user 'git'. The problem is, you're duplicating thamster's reply from 2012.Bedivere
I like this answer. However, for me this only works if I add IdentitiesOnly yes to my ssh config file.Chaddy
the problem with any solution that has you creating duplicate host entries with different aliases are two: 1. you need to remember them 2. some tooling will infer the http web interface of the remote from the ssh remote, this breaks it.Preference
B
111

The problem is when you have different remote repositories on the same host (say github.com), and you want to interact with them using different ssh keys (i.e. different GitHub accounts).

In order to do that:

  1. First you should declare your different keys in ~/.ssh/config file.

    # Key for usual repositories on github.com
    Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa
    
    # Key for a particular repository on github.com
    Host XXX
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_other_rsa
    

    By doing this you associate the second key with a new friendly name "XXX" for github.com.

  2. Then you must change the remote origin of your particular repository, so that it uses the friendly name you've just defined.

    Go to your local repository folder within a command prompt, and display the current remote origin:

    >git remote -v
    origin  [email protected]:myuser/myrepo.git (fetch)
    origin  [email protected]:myuser/myrepo.git (push)
    

    Then change origin with:

    >git remote set-url origin git@XXX:myuser/myrepo.git
    >git remote -v
    origin  git@XXX:myuser/myrepo.git (fetch)
    origin  git@XXX:myuser/myrepo.git (push)
    

    Now you can push, fetch... with the right key automatically.

Barehanded answered 9/5, 2019 at 20:31 Comment(4)
This sounds like exactly what I'm looking for, but I can't get it working. Whenever I run a git command I get: ssh: Could not resolve hostname helloworld-wp-github: Name or service not known fatal: Could not read from remote repository.Fetch
Did you add a new entry in your ~/.ssh/config ? This is how you tell ssh that your "helloworld-wp-github" is an alias for "github.com". Then, and only then, you can use your alias as remote server in git commands.Barehanded
Adding User git was what I was missing. You can test connection with ssh -vT XXX ( docs.github.com/en/authentication/troubleshooting-ssh/… )Limnetic
this is a horrible answer to be honest. you now have to remember all these special domain names and any tooling that relies on the git remote being correctly transferrable to a http web interface is now broken. what's that somerandomproject.github.com doesn't exist? oh no? dramalama! The correct solution is to use the core.sshCommand, bonus points if you persist it with your ~/.dotfiles/.gitconfig and make use of includeif logic 👍Preference
M
99

As stated here: https://superuser.com/a/912281/607049

You can configure it per-repo:

git config core.sshCommand "ssh -i ~/.ssh/id_rsa_example -F /dev/null"
git pull
git push
Molini answered 12/1, 2017 at 12:14 Comment(4)
What does -F /dev/null do? As far as I can see this will change configFile from the ~/.ssh/config default but why is that desired? To ensure a sandboxed command?Ecosystem
linuxcommand.org/man_pages/ssh1.html, specifies no config file, so when git will run ssh, no config file will be passed (in fact it's a kind of sandbox mode, just ignore user config default options) Original thread in superuser has more info about -FMolini
Why would you put this in your .bash_profile as an alias? You just run it once (for each repo). In general, use functions instead of aliases and your life will be easier; but both are slightly hard if you are confused about quoting.Hayman
git -c core.sshCommand="ssh -i ~/.ssh/{key}" clone {repo}Infirmary
F
68

The fastest and simplest way of doing it is by:

Clone your repo with ssh:

git -c core.sshCommand="ssh -i ~/.ssh/<your_key>" clone [email protected]:<user>/<repo>.git

then cd into you cloned repo and:

git config core.sshCommand 'ssh -i ~/.ssh/<your_key>'

To test it's working:

git --git-dir=/path/to/repo/.git pull

So you may wonder: why my created ssh key does not work after I planted the .pub in github and the private is in the default directory?

The documentation gives us a command that clarifies the issue: ssh -vT [email protected]

The output shows a list of ssh keys names git looks for. So, you may want to create your key with one of those names, or use the above process to include the one you need.

Fayre answered 1/10, 2021 at 21:25 Comment(3)
To add to this, you should be configuring this by using another feature of gitconfig: includeif.Preference
You can replace the two commands with this one command: git clone -c "core.sshCommand=ssh -i ~/.ssh/<your_key>" [email protected]:<user>/<repo>.git . Notice the -c option comes after clone, not before.Octosyllabic
-i is merely a suggestion without further flags. To avoid this heresy, expand it to ssh -o IdentitiesOnly=yes -o IdentityFile=~/.ssh/<your_key> --identity_file=~/.ssh/<your_key>.Preference
C
49
GIT_SSH_COMMAND="ssh -i /path/to/git-private-access-key" git clone $git_repo

or

export GIT_SSH_COMMAND="ssh -i /path/to/git-private-access-key"
git clone REPO
git push
Comfrey answered 18/1, 2019 at 15:45 Comment(1)
That is clean. I want to add GIT_SSH_COMMAND="ssh -i /path/to/git-private-access-key" git clone repo if anyone want to use it temporarily.Caveat
S
42

Way better idea to add that host or ip to the .ssh/config file like so:

Host (a space separated list of made up aliases you want to use for the host)
    User git
    Hostname (ip or hostname of git server)
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_(the key you want for this repo)
Shipwright answered 1/10, 2012 at 21:55 Comment(4)
That's useful, but makes you use the repo key for all interaction with that hostname. If there are other repos on the same server that require different keys, using a wrapper and telling git to use it with GIT_SSH is better.Dulse
That's not necessarily true. I use multiple keys for Github - one for work and one for my personal account. You don't have to put a domain name for "Host". You can put any kind of alias you want. For example, I use gh-home and gh-work as my hostnames and when I clone I use, for example, git clone git@gh-work:repo/project.git In my ~/.ssh/config I have two sections that both use github.com for HostName. They just have different IdentityFile and HostBalsaminaceous
@brettof86 this strategy works for the most part, but what do you do when a repository you are checking out depends on a gem which is also hosted on github? The the reference to the github repo in the Gemfile wont contain your "alias", well not unless you want to break things for other developers on the project...Laboy
The gist is here gist.github.com/justbrettjones/…Balsaminaceous
S
42

From Git version 2.10.0, you can configure this per repo or globally

git config core.sshCommand "ssh -i ~/.ssh/id_rsa_example -o 'IdentitiesOnly yes'"

This will specify for the current repo what ssh key will use. I assume if you want to specify this global only need to set the --global option.

Saddlery answered 23/3, 2021 at 15:12 Comment(3)
How do I specify this for checkout? I mean, I've just created a new empty folder, opened console, went inside this folder and executed this command. It tells me: fatal: not in a git directory.Rath
You need to initialize git, with git initSaddlery
Using WSL2 I had originally set the path using standard forward-slashes \ including the C:\Users path but had to alter it verbatim as you had it with the standard Unix path syntax ~/. This worked perfectly for my and especially helpful with the note about setting the --global option which was all but implied for most casesSerrano
O
37

This command clones the repo and configures the SSH key to use permanently:

git clone -c "core.sshCommand=ssh -i ~/.ssh/<key>" [email protected]:<user>/<repo>.git

Now, if you run git fetch, git pull, or git push, it will use the SSH key configured in core.sshCommand (saved in .git/config).

Octosyllabic answered 24/6, 2022 at 14:3 Comment(0)
E
33

I went with the GIT_SSH environment variable. Here's my wrapper, similar to that from Joe Block from above, but handles any amount of arguments.

File ~/gitwrap.sh

#!/bin/bash
ssh -i ~/.ssh/gitkey_rsa "$@"

Then, in my .bashrc, add the following:

export GIT_SSH=~/gitwrap.sh
Ecbatana answered 15/1, 2013 at 16:58 Comment(5)
I did set this on .bashrc. But when I login to openshift instance, it does not seems to be calling it. Am I missing something ?Redbreast
It fails with an error for me.. its not able to find the script event though its there.. not sure whats going on...error: cannot run /tmp/gitwrap.sh: No such file or directoryWildwood
If you face "No such file or directory" error, put full path of gitwrap.sh, for example /home/ubuntu/gitwrap.shKarmenkarna
you might want to add -o StrictHostKeyChecking=no to the ssh commandNerves
I tried to implement this, but I was not happy with the fact that I needed an extra script file to act as a wrapper, and when I checked the documentation, I found an easier way. You can use GIT_SSH_COMMAND to specify the command you want git to use. In my case (different private key), I had to do this: export GIT_SSH_COMMAND="ssh -i ~/.ssh/my_alternative_private_key" and then continue to use git as normal in the script.Vyborg
I
19

If none of the other solutions here work for you, and you have created multiple ssh-keys, but still cannot do simple things like

git pull

then assuming you have two ssh key files like

id_rsa
id_rsa_other_key

then inside of the git repo, try:

# Run these commands INSIDE your git directory
eval `ssh-agent -s`
ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/id_rsa_other_key

and also make sure your github default username and userid are correct by:

# Run these commands INSIDE your git directory
git config user.name "Mona Lisa"
git config user.email "[email protected]"

See https://gist.github.com/jexchan/2351996 for more more information.

Incident answered 21/11, 2018 at 16:51 Comment(3)
Note if you get Could not open a connection to your authentication agent., try $ eval `ssh-agent -s`, and try again.Incident
Why do you think it matters in which directory you run ssh-add?Hayman
@BenCartwright Because you are modifying local settings, not global settings. This approach modifies .git inside the repo not the git program globally. You can use --global to set global username and email.Incident
A
19

2021. If you're on a Mac.

Say you have an ubuntu server on aws, which you normally connect to like this:

% ssh -i blah/yourkeypair.pem [email protected]

In terminal just

% export GIT_SSH_COMMAND="ssh -i /Users/fattie/Desktop/blah/yourkeypair.pem"

After you have done that. You can then freely ...

% git clone [email protected]:/home/ubuntu/teste.git  

That will clone the repo on your server to your local folder "teste",

you can then freely when in teste/ do the usual commands such as ...

% git push origin master

and so on.

--

Note also: https://mcmap.net/q/14310/-git-error-remote-unpack-failed-unable-to-create-temporary-object-directory-by-creating-new-branch


As for on the server, it seems you basically

] git clone --bare the-actual-folder teste.git

and then in teste.git

] git init --bare --shared
Aport answered 27/4, 2021 at 16:46 Comment(0)
F
16

I just needed to add the key and then rerun the git clone.

ssh-add ~/.ssh/id_rsa_mynewkey
eval $(ssh-agent -s)
git clone [email protected]:mycompany/myrepo.git
Flyleaf answered 13/5, 2020 at 1:44 Comment(1)
Thank you! After doing the ssh-add i got an error about the agent and then I found this answer which helped: https://mcmap.net/q/12599/-could-not-open-a-connection-to-your-authentication-agentKrystinakrystle
B
14

When you need to connect to github with a normal request (git pull origin master), setting the Host as * in ~/.ssh/config worked for me, any other Host (say, "github" or "gb") wasn't working.

Host *
    User git
    Hostname github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_xxx
Beforehand answered 6/5, 2013 at 4:34 Comment(3)
Might as well leave the entire "Host *" line out then.Canned
It probably wasn't working because it didn't match your remote URL. If you want to use Host my-host-alias, you have to set remote.origin.url=git@my-host-alias:[username]/[repo].git.Marquetry
Thanks a lot! I didn't have a config file and I kept getting Permission denied (publickey). fatal: Could not read from remote repository. error and making new keys didn't help.Bracteole
T
14

Many of these solutions looked enticing. However, I found the generic git-wrapping-script approach at the following link to be the most useful:

How to Specify an ssh Key File with the git command

The point being that there is no git command such as the following:

git -i ~/.ssh/thatuserkey.pem clone [email protected]:/git/repo.git

Alvin's solution is to use a well-defined bash-wrapper script that fills this gap:

git.sh -i ~/.ssh/thatuserkey.pem clone [email protected]:/git/repo.git

Where git.sh is:

#!/bin/bash

# The MIT License (MIT)
# Copyright (c) 2013 Alvin Abad
# https://alvinabad.wordpress.com/2013/03/23/how-to-specify-an-ssh-key-file-with-the-git-command

if [ $# -eq 0 ]; then
    echo "Git wrapper script that can specify an ssh-key file
Usage:
    git.sh -i ssh-key-file git-command
    "
    exit 1
fi

# remove temporary file on exit
trap 'rm -f /tmp/.git_ssh.$$' 0

if [ "$1" = "-i" ]; then
    SSH_KEY=$2; shift; shift
    echo "ssh -i $SSH_KEY \$@" > /tmp/.git_ssh.$$
    chmod +x /tmp/.git_ssh.$$
    export GIT_SSH=/tmp/.git_ssh.$$
fi

# in case the git command is repeated
[ "$1" = "git" ] && shift

# Run the git command
git "$@"

I can verify that this solved a problem I was having with user/key recognition for a remote bitbucket repo with git remote update, git pull, and git clone; all of which now work fine in a cron job script that was otherwise having trouble navigating the limited-shell. I was also able to call this script from within R and still solve the exact same cron execute problem (e.g. system("bash git.sh -i ~/.ssh/thatuserkey.pem pull")).

Not that R is the same as Ruby, but if R can do it... O:-)

Thrower answered 21/2, 2015 at 0:5 Comment(1)
Apart from the syntax, how is this better than GIT_SSH_COMMAND="ssh -i ~/.ssh/thatuserkey.pem" git clone clone [email protected]:/git/repo.git as per Robert Jack Will's answer?Marquetry
C
13

A lot of good answers, but some of them assume prior administration knowledge.

I think it is important to explicitly emphasize that if you started your project by cloning the web URL - https://github.com/<user-name>/<project-name>.git
then you need to make sure that the url value under [remote "origin"] in the .git/config was changed to the SSH URL (see code block below).

With addition to that make sure that you add the sshCommmand as mentioned below:

user@workstation:~/workspace/project-name/.git$ cat config
[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    sshCommand = ssh -i ~/location-of/.ssh/private_key -F /dev/null <--Check that this command exist
[remote "origin"]
    url = [email protected]:<user-name>/<project-name>.git  <-- Make sure its the SSH URL and not the WEB URL
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master

Read more about it here.

Catalogue answered 29/2, 2020 at 21:23 Comment(1)
Solid answer, provides info for project level config instead of system wide config. Other answers seem to ignore that you basically only run into this problem if you don't have a system wide configuration!Niela
E
9

if you have directory on your path where you want to sign with a given identifyfile you can specify to use a specific identify file via the .ssh/config file by setting the ControlPath e.g.:

host github.com
  ControlPath ~/Projects/work/**
  HostName github.com
  IdentityFile ~/.ssh/id_work
  User git

Then ssh will use the specified identity file when doing git commands under the given work path.

Eyewitness answered 14/3, 2019 at 12:41 Comment(3)
Found out later that you can also set the properties ControlMaster auto and ControlPersist yes, so that you do not need to retype the password every time. Found the info in this articleEyewitness
ControlPath Specify the path to the control socket used for connection sharing as described in the ControlMaster section above or the string ''none'' to disable connection sharing. In the path, '%l' will be substituted by the local host name, '%h' will be substituted by the target host name, '%p' the port, and '%r' by the remote login username. It is recommended that any ControlPath used for opportunistic connection sharing include at least %h, %p, and %r. This ensures that shared connections are uniquely identified.Menagerie
actually this sounds like an unintentional side effect of the proper use of ControlPathPreference
V
9

Why don't you just add location of identity key to git config file for a particular repo like this:

cd .git

vi config

[core]
    sshCommand = ssh -i <IDENTITY_KEY_LOCATION> -o IdentitiesOnly=yes

That's all you need.

Vivacious answered 23/1, 2023 at 16:26 Comment(2)
Is this in the repo? How do you then clone it in the first place? How does it work when others clone it, or I use a different machine?Permatron
GIT_SSH_COMMAND="ssh -i <IDENTITY_KEY_LOCATION> -o IdentitiesOnly=yes" git clone … and then this answer.Retrench
A
5

In Windows with Git Bash you can use the following to add a repository

ssh-agent bash -c 'ssh-add "key-address"; git remote add origin "rep-address"'

for example:

ssh-agent bash -c 'ssh-add /d/test/PrivateKey.ppk; git remote add origin [email protected]:test/test.git'

Which private key is in drive D, folder test of computer. Also if you want to clone a repository, you can change git remote add origin with git clone.

After enter this to Git Bash, it will ask you for passphrase!

Be Aware that openssh private key and putty private key are different!

If you have created your keys with puttygen, you must convert your private key to openssh!

Alexipharmic answered 25/12, 2016 at 22:16 Comment(1)
noone should be using putty in 2022. windows provides proper ssh support now.Preference
O
5

Most of the answers given here do not explain the details for the most basic usage.

After you have setup a server (in this case a linux server) in the cloud, you connect to it using ssh from the terminal.

From your computer, add the private key dyson-ubuntu-vm.pem which is given to you by your cloud services provider such as Azure, AWS etc to your .ssh configuration on your local machine like this:

Copy the .pem file to the /home/ssenyonjo/.ssh folder, then open /home/ssenyonjo/.ssh/config file and add the following entry:

Host 20.85.213.44
  HostName 20.85.213.44
  User Dyson
  IdentityFile /home/ssenyonjo/.ssh/dyson-ubuntu-vm.pem
  IdentitiesOnly yes

Now from your terminal, access the cloud linux server like so:

ssh [email protected]

When that works, create a git project on the cloud server like so:

Dyson@dyson-ubuntu-vm:~/projects$ git init --bare s2

Now come back to your local machine and clone that empty repository like so:

ssenyonjo@ssenyonjo-pc:~/Projects/mastering-git$ git clone ssh://[email protected]/home/Dyson/projects/s2

If you see an error that looks something like: fatal: Could not read from remote repository, It means you're accessing the wrong folder. Ensure you have outlined the right path from the root to the created repository.

If you dont want to setup a config file but want to access the ssh server that requires a key, you can use below command:

GIT_SSH_COMMAND='ssh -i ~/Projects/aws/keys/aws_ubuntu.pem'  git clone ssh://[email protected]/home/ubuntu/projects/mastering-git/rand 

You can export the command to continue using it for other tasks like git push and git pull

export GIT_SSH_COMMAND='ssh -i ~/Projects/aws/keys/aws_ubuntu.pem'

See: https://mcmap.net/q/14116/-how-to-specify-the-private-ssh-key-to-use-when-executing-shell-command-on-git

Obtrude answered 2/10, 2021 at 17:23 Comment(0)
P
4

To have GIT_SSH_COMMAND environment variable work under Windows(CMD) instead of:

set GIT_SSH_COMMAND="ssh -i private_key_file"

Use:

set "GIT_SSH_COMMAND=ssh -i private_key_file"

The quote has to be like

set "variable=value" 

Some backgorund: https://mcmap.net/q/13512/-how-to-set-environment-variables-with-spaces

Psalms answered 7/1, 2020 at 9:31 Comment(0)
Y
4

The problem with this method is, at least when running by bash.exe on Windows, that it will create a new process every time which will remain dormant.

ssh-agent bash -c 'ssh-add /somewhere/yourkey; git clone [email protected]:user/project.git'

If you want want to use that for syncig repo on schedule then you need to add "&& ssh-agent -k" at the end.

Something like:

ssh-agent bash -c 'ssh-add C:/Users/user/.ssh/your_key; git -C "C:\Path\to\your\repo" pull && ssh-agent -k' 

ssh-agent -k will kill the process when it's done.

Yann answered 24/4, 2020 at 8:30 Comment(0)
A
4

Also, as a simple "workaround", if you don't really need it that often:

Remove all ssh identities from the currently running ssh agent (not physically).

ssh-add -D

Re-add the one you need to work with to your currently running ssh-agent

ssh-add ~/.ssh/MyProperProfile

Do the gits

Optionally - revert by adding other identities (or all of 'em).

Armenta answered 31/1, 2023 at 11:15 Comment(2)
NOTE: The command will delete all your keys!!! @Der Zinger Please Note this in your post with a Bold text!Ariosto
I don't really get what this "warning" should be about sir. This command (ssh-add -D) quote: Removes all identities from the agent.. It does not delete anything from anywhere. The actual keys are still physically there, exactly where they where before that command, and can be easily re-added with the next command I've listed. The only thing this command do - makes sure that ssh-agent (and everything that relies on it, like git) does not "know" about your keys.Armenta
J
3

This is an extension to @VonC's answer. Please read it first.

Use case is I need to use both personal and work GitHub accounts using SSH. I want to use work SSH key as default as my projects will internally have other work repos as dependency. So cloning them should work seamlessly.

Steps I followed are:

  • Generate default SSH key and add it to work git account.

  • Generate personal SSH key in a separate file and add it to personal git account.

  • Add the following function code in your .bashrc or .zshrc file and source it.

     gclone() { 
         # Clone the repo-url using personal ssh-key
         git -c core.sshCommand="ssh -i path_to_personal_key" clone "$1" &&
    
         # Extract repo name from URL using "awk" and switch to that folder using "cd" 
         cd $(awk '{ sub(/.*\//, ""); sub(/\.git.*/, ""); print }' <<< "$1") &&
    
         # Set personal ssh-key as default for this repo 
         git config core.sshCommand "ssh -i path_to_personal_key";
     }
    
  • Use gclone command to clone repos using personal SSH key and set the repo to use that key as default.

  • Use normal git clone command to clone repos with default(work) SSH key.

Jasmin answered 19/6, 2022 at 22:36 Comment(0)
W
3

Clone in one command

git -c core.sshCommand='ssh -i /path/to/key/' clone [email protected]:your_repository.git /path/target/clone --branch git_branch_name
Wellspring answered 7/10, 2022 at 17:24 Comment(0)
D
3

If you are getting an SSH permission denied Error when running commands like git push, pull, or fetch even after you have copied your SSH public key to GitHub.

NOTE
Use --local when you're in a local git repo,
but use --global when you want to apply to all repos

Use this:

git config --add --local core.sshCommand 'ssh -i /path-to-ssh-private-key'

E.g

git config --add --local core.sshCommand 'ssh -i /home/user/.ssh/github-key'

You're done!

Optionally you can verify your change with this:

git config --local --get core.sshCommand
Dnepropetrovsk answered 28/1 at 1:29 Comment(1)
This worked for me. And the simplestPatrickpatrilateral
H
1

I use zsh and different keys are loaded to my zsh shell's ssh-agent automatically for other purposes (i.e. access to remote servers) on my laptop. I modified @Nick's answer and I'm using it for one of my repos that needs to be refreshed often. (In this case it's my dotfiles which I want same and latest version across my all machines, wherever I'm working.)

bash -c 'eval `ssh-agent`; ssh-add /home/myname/.dotfiles/gitread; ssh-add -L; cd /home/myname/.dotfiles && git pull; kill $SSH_AGENT_PID'
  • Spawn an ssh-agent
  • Add read-only key to agent
  • Change directory to my git repo
  • If cd to repo dir is successful, pull from remote repo
  • Kill spawned ssh-agent. (I wouldn't want many of agents lingering around.)
Holothurian answered 21/8, 2017 at 3:15 Comment(0)
Z
1

for the gitlab RSAAuthentication yes

Host gitlab.com
  RSAAuthentication yes
  IdentityFile ~/.ssh/your_private_key_name
  IdentitiesOnly yes

doc is here

Zane answered 2/9, 2017 at 0:7 Comment(1)
doesn't appear to be mentioned on the link you provided any moreIntelligencer
E
1

You need to create a ~/.ssh/config as below

Host <Your bitbucket server>
User <userid>
Hostname <Your bitbucket server as above>
IdentitiesOnly yes
IdentityFile ~/.ssh/id_rsa<file> This is your private key file

permission as below

-rw------- $HOME/.ssh/config

Add your public key into your git (cat ~/.ssh/id_rsa_pub [or simillar name])

and then git clone as below

git clone ssh://[email protected]/userid/test.git
Elane answered 7/12, 2018 at 6:46 Comment(0)
M
1

I was able to resolve this requirement with following command option to git clone --config core.sshCommand="ssh -i /d/repos/ssh/prod-a/.ssh/id_ed25519"

Magically answered 30/5, 2023 at 9:22 Comment(0)
O
1

In my case I've got two accounts with different ssh keys. I wanted to clone a repository, so how i did it:

id_ed25519 - is the name of second key, usually default key is: ~/.ssh/id_rsa

$ eval `ssh-agent -s`

$ ssh-add ~/.ssh/id_ed25519

If you use a Github you can check correct auth with command below:

$ ssh -T -p 443 [email protected]

Clone or Pull code with command below:

(for the first time)

$ git clone [email protected]:username/path-somewhere.git

(for the next time)

$ git pull
Ormond answered 4/2 at 7:41 Comment(0)
I
0

You could use GIT_SSH environment variable. But you will need to wrap ssh and options into a shell script.

See git manual: man git in your command shell.

Icebound answered 28/10, 2011 at 12:9 Comment(0)
M
0

If SSH port number is not 22(default), add Port xx in ~/.ssh/config

In my case (synology),

Host my_synology
    Hostname xxxx.synology.me
    IdentityFile ~/.ssh/id_rsa_xxxx
    User myname
    Port xx

Then clone using Host title in config. ("my_synology". to avoid @chopstik 's "*")

git clone my_synology:path/to/repo.git
Malissa answered 31/10, 2017 at 15:15 Comment(0)
B
0

If you're like me, you can:

  • Keep your ssh keys organized

  • Keep your git clone commands simple

  • Handle any number of keys for any number of repositories.

  • Reduce your ssh key maintenance.

I keep my keys in my ~/.ssh/keys directory.

I prefer convention over configuration.

I think code is law; the simpler it is, the better.

STEP 1 - Create Alias

Add this alias to your shell: alias git-clone='GIT_SSH=ssh_wrapper git clone'

STEP 2 - Create Script

Add this ssh_wrapper script to your PATH:

#!/bin/bash
# Filename: ssh_wrapper

if [ -z ${SSH_KEY} ]; then
    SSH_KEY='github.com/l3x'  # <= Default key
fi
SSH_KEY="~/.ssh/keys/${SSH_KEY}/id_rsa"
ssh -i "${SSH_KEY}" "$@"

EXAMPLES

Use github.com/l3x key:

KEY=github.com/l3x git-clone https://github.com/l3x/learn-fp-go

The following example also uses the github.com/l3x key (by default):

git-clone https://github.com/l3x/learn-fp-go

Use bitbucket.org/lsheehan key:

KEY=bitbucket.org/lsheehan git-clone [email protected]:dave_andersen/exchange.git

NOTES

Change the default SSH_KEY in the ssh_wrapper script to what you use most of the time. That way, you don't need to use the KEY variable most of the time.

You may think, "Hey! That's a lot going on with an alias, a script and some directory of keys," but for me it's convention. Nearly all my workstations (and servers for that matter) are configured similarly.

My goal here is to simplify the commands that I execute regularly.

My conventions, e.g., Bash scripts, aliases, etc., create a consistent environment and helps me keep things simple.

KISS and names matter.

For more design tips check out Chapter 4 SOLID Design in Go from my book: https://www.amazon.com/Learning-Functional-Programming-Lex-Sheehan-ebook/dp/B0725B8MYW

Hope that helps. - Lex

Bonhomie answered 31/12, 2018 at 5:40 Comment(1)
it's much easier to just use includeif and a series of config files that set teh sshCommandPreference
I
0

Don't overcomplicate things, just use ssh-add to add a temporary identity

alias gpullpersonal='ssh-add mykey;git pull;ssh-add -D'
alias gpullprofessional='ssh-add myotherkey;git pull;ssh-add -D'
Infidel answered 4/3, 2023 at 17:58 Comment(0)
M
-6

You can try sshmulti npm package for maintaining multiple ssh key.

Middlebrow answered 4/3, 2020 at 16:22 Comment(1)
NPM package?! This should be a machine-related problem, useless yours is an application-relatedDnepropetrovsk

© 2022 - 2024 — McMap. All rights reserved.