How to Connecting to GitHub with SSH key using Shell script

Ridmi Rangika
2 min readMar 23, 2019

--

This is something that I had to work on as a part of a task which is allocated for me. Let me explain the background of the issue that I had to face. I had to clone a Github repository in aws instance. I used a python script to do the cloning and when I try to clone the git repository through python it didn't allow me to do it. I started to search how to do this but no luck ☹️. Finally found a way to do it by using a shell script.

First, we need to create a private SSH key to your Github account. (You can follow this link to create an SSH key) Through the python script, we need to pass the private SSH key, git repository that you want to clone and branch if need.

subprocess.call(['bash', 'clone_repo.sh', sshKeyvalue, git_branch, git_repo_url])

Above command will execute the shell script. I used python subprocess module to run the shell command in python. clone_repo.sh is the shell script that includes the git clone process. sshKeyvalue assigned private SSH key value, rest of two parameters for git repository Branch and the URL.

  • In shell script first, we need to add GitHub key to the known host in the instance.
ssh-keyscan -H "github.com" >> ~/.ssh/known_hosts
  • Needs to start the SSH-Agent. SSH-Agent is to hold private keys used for public key authentication.
eval "$(ssh-agent -s)"
  • Write private ssh key that we passed from python script to id-rsa file. ($1 parameter assigned the value of sshKeyvalue)
echo "$1" > ~/.ssh/id_rsa

We need to set the permission for the id_rsa file. Depends on the instance that we try to clone the git repository, root path can be varied. For that, we need to find the current username and set permission.

if [ $username == "centos" ]; then
chmod 600 /home/centos/.ssh/id_rsa
else
chmod 600 /home/ubuntu/.ssh/id_rsa
fi
  • Then we need to add the SSH key to the agent
ssh-add ~/.ssh/id_rsa

Now you should be able to clone the product with following shell command. 😊 ($2 & $3 parameter assigned the value of git branch & git URL)

ssh-agent bash -c "ssh-add ~/.ssh/id_rsa; git clone --branch $2 $3"

Cheers!!!

--

--

Ridmi Rangika

Associate Technical Lead | QE experienced engineer | ISTQB Certified Tester | Fashion designer | In <3 with Docker