1

The goal is to get a bash script that connects to EC2 to download offsite backups. I have this, but I have to keep running them from the terminal manually as they fail from the crontab with the error "Permission denied (publickey)", so the key is obviously failing to add.

There's obviously a hole in my understanding. I've been tinkering for a couple of hours trawling Google and still haven't got it working. What am I doing wrong in terms of getting the script to add the keys itself?

#!/bin/sh
# Add the client key so we can SSH in
eval "$(ssh-agent)"
ssh-add ec2-key.pem

# Download the web file backup.
# Example file web1_2013-06-30_00-30.tar.gz
WEBDATE=`date +"%Y-%m-%d"`;
echo $(date) " - Web Backup >> Running secure copy: scp {user}@{ip}:/var/backup/web1/web1_$WEBDATE* site-files/"
scp {user}@{ip}:/var/backup/web1/web1_$WEBDATE* site-files/
... etc ...
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
JamesNZ
  • 482
  • 5
  • 17
  • Where are you expecting that script to be being run from? What working directory? Where does that `ec2-key.pem` file live? – Etan Reisner Dec 22 '14 at 22:22
  • Both the shell script and key file are in /data/backups/{client_dir_here}. So they're in the same directory. – JamesNZ Dec 22 '14 at 22:45
  • 1
    Relative paths in a script do not resolve relatively to the script directory, but to the directory you run the script from. Make sure you run the script from `/data/backups/{client_dir_here}`. – Martin Prikryl Dec 23 '14 at 07:29

1 Answers1

0

Use the full path to the key the way you use the full path to the script and the output files and it should work.

If you want to have the script load the key from the same directory as the script automatically then see Getting the source directory of a Bash script from within and http://mywiki.wooledge.org/BashFAQ/028 for ways/how to do that.

Community
  • 1
  • 1
Etan Reisner
  • 77,877
  • 8
  • 106
  • 148