I've been struggling to crontab automate a git push process with ssh, and it's proving tricky to setup a key with the ssh agent. Starting with a basic script to test the agent:
# set paths (all examples)
source /etc/profile
export PATH=$PATH:/Users/myusername/.ssh
eval "$(ssh-agent)" > ssh_agent.txt
/usr/bin/ssh-add -l >> ssh_agent.txt
..which outputs the following:
Agent pid 16062
The agent has no identities.
So the agent is active. Now to add the key and check it's registered with the agent. In iTerm2 manually this works ok:
/usr/bin/ssh-add /Users/myusername/.ssh/id_rsa
2048 [key fingerprint] /Users/myusername/.ssh/id_rsa (RSA)
I try to replicate this inside a crontab job, using this script:
/usr/bin/ssh-add /Users/myusername/.ssh/id_rsa
/usr/bin/ssh-add -l >> ssh_agent.txt
..which reports The agent has no identities
to file, and the following via "You have mail in /var/mail/myusername"
:
[email metadata]
Enter passphrase for /Users/myusername/.ssh/id_rsa:
So the key is trying to load but is catching at the passphrase prompt. Here I want to use expect
to give it the passphrase, as described in this unix.stackexchange answer (which looks like it should work in OSX):
#!/usr/bin/expect -f
/usr/bin/ssh-add /Users/myusername/.ssh/id_rsa
expect "Enter passphrase for /Users/myusername/.ssh/id_rsa:"
send "mypassphrase\n";
interact
The mail error response is:
Enter passphrase for /Users/myusername/.ssh/id_rsa:
couldn't read file "Enter passphrase for /Users/myusername/.ssh/id_rsa:": no such file or directory
/Users/myusername/test/crontest.sh: line 17: send: command not found
/Users/myusername/test/crontest.sh: line 18: interact: command not found
So I tried an alternative configuration based on this SO answer:
#!/usr/bin/expect -f
expect -c "
/usr/bin/ssh-add /Users/myusername/.ssh/id_rsa
expect \"Enter passphrase for /Users/myusername/.ssh/id_rsa: \"
send \"mypassphrase\n\";
interact
"
.. and get the following mail error report:
invalid command name "/usr/bin/ssh-add"
while executing
"/usr/bin/ssh-add /Users/myusername/.ssh/id_rsa"
Could not open a connection to your authentication agent.
I don't understand the problem here - ssh agent works and the key seems accessible so what is this 'connection' issue? I've tried other configurations for expect
without success. Very grateful for assistance.
eval "$(ssh-agent)"
needs to be included in a working script as that actually initiates the agent.