0

Issue

  1. I want to automate downloading a file via SFTP
  2. I set up an SFTP server and a keying mechanism
  3. I have created a simple bash script - script.sh
  4. I added an entry in cron for the script

The script, script.sh:

#!/bin/bash  
sftp user@server:/home/user/file.txt  
exit 0

Executing the script manually works fine (text file is saved in home directory), but adding script.sh (with proper permissions) to crontab does nothing.

The crontab entry:

* * * * * /home/user/script.sh

For authentication I used ssh-keygen to create a set of keys (private, public) and set up cross authentication to the SFTP server.

For script automation I used keychain for password-less authentication.

Currently

Currently, I have a script called script.sh located in the "user" home directory (/home/user/).

When run by root manually, the script gets the file from the SFTP server, and places it in /home/user/.

It does not perform this action when run from a cron job. In cron, the sftp command gets an error.

Ideas?

Working on it

  1. Changing the HOME variable on /etc/crontab did not solve the issue
  2. Stating full paths in script.sh did not solve the issue
  3. Stating PATH variable in script.sh did not solve the issue
  4. I catched the error from the sftp command - it's 255

executing the script manually (./script.sh) still works flawlessly though...

Zanna
  • 72,312

1 Answers1

1

A working example:

a simple script named hello.sh that appends to a text file the word hello (uses full paths for each command):

note myuser is the name of your user

#!/bin/bash
printf 'hello' >> /home/myuser/hello.txt

Make the script executable using chmod +x hello.sh

The crontab entry that runs every minute you can change that accordingly to your needs:

* * * * * /home/myuser/hello.sh

Some details:

  • Each cron job runs as the user which registered it. If the root user registers a cron job, this job will run with root privileges.

  • If a non root user registers a cron job, this job will run with the aforementioned user's privileges;if the job requires root privileges it will fail because it is initiated by the non root user...

  • Better call commands and script using full paths just to be sure that cron can find and call them correctly, else it may fail without useful feedback.

Zanna
  • 72,312
Stef K
  • 4,886