Mis
Mis

Reputation: 33

Using the ssh agent inside a python script

I'm pulling and pushing to a github repository with a python script. For the github repository, I need to use a ssh key.

If I do this manually before running the script:

eval $(ssh-agent -s)
ssh-add ~/.ssh/myprivkey

everything works fine, the script works. But, after a while, apparently the key expires, and I have to run those 2 cmds again

The thing is, if I do that inside the python script, with os.system(cmd), it doesn't work, it only works if I do that manually

I know this must be a messy way to use the ssh agent, but I honestly don't know how it works, and I just want the script to work, that's all

The script runs once an hour, just in case

Upvotes: 2

Views: 3432

Answers (2)

lrcto_1
lrcto_1

Reputation: 37

Consider defining the ssh key path against a host of github.com in your ssh config file as outlined here: https://stackoverflow.com/a/65791491/14648336

If Linux then at this path ~/.ssh/ create a file called config and input something similar to in the above answer:

Host github.com
    HostName github.com
    User your_user_name
    IdentityFile ~/.ssh/your_ssh_priv_key_file_name

This would save the need for starting an agent each time and also prevent the need for custom environment variables if using GitPython (you mention using Python) as referenced in some other SO answers.

Upvotes: 0

VonC
VonC

Reputation: 1323145

While the normal approach would be to run your Python script in a shell where the ssh agent is already running, you can also consider an alternative approach with sshify.py

# This utility will execute the given command (by default, your shell)
# in a subshell, with an ssh-agent process running and your
# private key added to it. When the subshell exits, the ssh-agent
# process is killed.

Upvotes: 1

Related Questions