Git commit with gitpython and SSH key

Eva(Tzuni) Hsieh
2 min readJan 5, 2019

--

The Pythoncat by Cameron McEfee

Using Python to commit files to Git is easy, but having a fully CI/CD automation process to setup Git SSH for the Python script is not so easy since you cannot handle any prompt during the installation process.

If you need to use Python programmatically commit files to Git by using headless accounts or even setup CI/CD automation process; this article might be able to help you.

1. Prepare SSH Private Key

Before we started, the first thing you need is the SSH private key which associate to the Git account you are going to use, headless or not.

$ sudo cp <SSHPrivateKey> /etc/ssh/my_gitpython_key
$ sudo chmod 600 /etc/ssh/my_gitpython_key

2. Create Custom SSH Script

By default, git will just use the system default ssh command.

Since we want to commit to Git programmatically and there’s no way to setup ssh-agent without human involving; we need to create a new ssh script for our Python script.

$ sudo vim /usr/local/bin/my_gitpython_ssh

This is what looks like in this new custom ssh script:

#!/bin/bash
ssh -i /etc/ssh/my_gitpython_key -oIdentitiesOnly=yes -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null "$@"

What we are doing in here is to create a wrap of ssh command to make sure that whenever Git using ssh to commit the file, it will always by default using the correct SSH private key and not asking you to confirm the .ssh/know_host while connecting to the git server for the first time.

Don’t forget to change the file mode for this new custom ssh script by using this command:

$ sudo chmod a+x /usr/local/bin/my_gitpython_ssh

3. Create Python Git class

This is a very basic Python Git class which gives you an idea about how to use gitpython library to clone/commit/add/push files to your Git repository.

Simply install gitpython package with pip command:

$ pip install gitpython

To keep this example as simple as possible, you will need to provide an existing repository which has initialed already.

Copy below file then save as git_example.py.

Execute this file with sudo permission because our private key is under /etc/ssh which requires sudo permission.

$ sudo -E git_example.py

If you are having permission issue when committing to Git, make sure the account you are using has write permission to your repository.

References

--

--

Eva(Tzuni) Hsieh

Software Engineer. Love Python and Go; JavaScript/Node.js sometimes.