cron git push with ssh key

2019-02-05 09:08发布

问题:

I setup a ssh key for github account, so I don't have to enter the password every time, it works fine. Here is the script I use:

#!/bin/bash
git push origin master

But when I use cron to run it, it will not use my ssh key. Here is the output:

Permission denied (publickey)
fatal: The remote end hung up unexpectedly

I search around and found some articles, but none of them solve my problem. Here are the articles I found(and a lot more):

https://askubuntu.com/questions/110565/why-is-git-not-using-my-pubkey-with-crontab

https://unix.stackexchange.com/questions/35466/how-to-perform-git-push-using-crontab

git push via cron

Can anybody give me a step to step instructions to solve this problem?

回答1:

As mentioned in one of your thread, you need to point the root user which executes your cron script to the right HOME (the one which contains $HOME/.ssh/id_rsa(.pub), your public and private keys.

#!/bin/bash
HOME=/home/yourAccount git push origin master

If that doesn't work, start debugging your ssh command with

#!/bin/bash
HOME=/home/yourAccount ssh -Tvvv yourGitServer

And check that with first a simple private key (not protected by a passphrase).
Then, if you need a passphrase, make sure your ssh-agent is running in order to cache said passphrase (or using keychain, as I mentioned before).

According to your logs, the public ssh key is proposed, but rejected.

debug1: Trying private key: /home/jack/.ssh/id_rsa
debug3: no such identity: /home/jack/.ssh/id_rsa

Double-check "BitBucket Set up SSH for Git", and make sure your id_rsa and id_rsa.pub are there, with the right protection.

Check also your id_rsa.pub has been added to your BitBucket account (as one line).



回答2:

Based on your comments, I don't really understand why your script wouldn't work in cron. We can try a few things to clear things up.

Add a configuration in ~/.ssh/config for the user running the cron job like this:

Host github-project1
User git
HostName github.com
IdentityFile /path/to/github.project1.key
#or like this:
#IdentityFile ~/.ssh/github.project1.key

Then in your git working tree add a new remote like this:

git remote add github-project1 github-project1:USER/PROJECT.git

In the url there, github-project1:user/project.git, change only USER and PROJECT to the right values for your project, but leave github-project1 as is: it must match the value of the Host setting in the ssh configuration we just added.

Finally, change the script to use this new remote:

#!/bin/bash
git push github-project1 master

Test the script first in the shell, and then in cron.



标签: git ssh cron