Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git: access a remote repository over ssh using a key file but without using ~/.ssh/config

Tags:

git

ssh

config

Is it possible to access (fetch/push) a remote repository using ssh and an identity file (with the private key) without adding an entry in the file ~/.ssh/config such as:

Host tingle
  HostName 111.222.333.444
  User git
  IdentityFile c/tmp/my_id_rsa

Everything works fine when configuring the ~/.ssh/config file. However we have a script which clones from a remote repo, checks out, starts testing, commits results and pushes them. The script need to run on any machine without touching the ssh config file.

like image 672
Paul Pladijs Avatar asked Jun 07 '16 18:06

Paul Pladijs


People also ask

Do I need SSH key to git clone?

Get an SSH key for your site The Git system uses the SSH protocol to transfer data between the server and your local computers. This means that in order to clone the repository you need to have SSH access to your website.

How do I push a file to GitHub using SSH key?

Log into your GitHub account and choose your desired repository (which you want to connect to your web application). Then, navigate to Settings and click on Deploy Keys. Click on Add Deploy Key button to add the SSH key we copied in step 3. Paste the content into the Key field on Github.


2 Answers

You can use the variable $GIT_SSH, see the documentation, to set a program that is invoked instead of ssh.

That way you can, e.g. do GIT_SSH=/my/own/ssh git clone https://my.own/repo.git

Adapt the contents of /my/own/ssh to your own need, e.g.:

#!/bin/bash
# Wrapper for ssh, to use identity file and known hosts file
exec /usr/bin/ssh -i /my/own/identity_file-o UserKnownHostsFile=/my/own/hosts.file "$@"

As far as I know this is currently the only way to do this without rather untidy path manipulations.

like image 84
M. Glatki Avatar answered Oct 22 '22 09:10

M. Glatki


You could override the $GIT_SSH environment variable to use your own private key:

First, create a wrapper script. Let assume we call it gitssh.sh:

#!/bin/bash
ssh -i /path/to/mykey "$@"

Then, point $GIT_SSH to it:

export GIT_SSH=/path/to/gitssh.sh

Now, whenever you run a git command over ssh, it will be substituted with this script, and references your key.

like image 31
Mureinik Avatar answered Oct 22 '22 08:10

Mureinik