سؤال

I am trying to archive my localhost's root folder with tar and want to automate it's execution on a daily basis with crontab. For this purpose, I created a 'backupfolder' in my personal folder. I am running on Ubuntu 12.04.

The execution of tar in the command line works fine without problems:

sudo tar -cvpzf backupfolder/localhost.tar.gz /var/www

However, when I schedule the command for a daily backup (let's say at 17.00) in sudo crontab -e, it is not executing, i.e. the backup does not update using the following command:

0 17 * * * sudo tar -cpzf backupfolder/localhost.tar.gz /var/www

I already tried the full path home/user/backupfolder/localhost.tar.gz without success.

var/log/syslog gives me the following output for the scheduled execution:

Feb  2 17:00:01 DESKTOP-PC CRON[12052]: (root) CMD (sudo tar -cpzfbackupfolder/localhost.tar.gz /var/www)
Feb  2 17:00:01 DESKTOP-PC CRON[12051]: (CRON) info (No MTA installed, discarding output)

/etc/crontab specifies the following path:

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

I assume that crontab is not executing as this is a sudo command.

Is there a way how I can get this running? What is the recommended, safe way if I don't want to hardcode my root password?

هل كانت مفيدة؟

المحلول

Well, the command that works for you is

sudo tar -cvpzf backupfolder/localhost.tar.gz /var/www

Which means, you have to run the command with sudo access, and it will not work from within your crontab.

I would suggest adding the cron job to the root user's crontab.

Basically, do

sudo crontab -e

And add an entry there

0 17 * * * cd /home/user/backupfolder && tar -cpzf localhost.tar.gz /var/www

If that doesn't work, add the full path of tar (like /bin/tar).

Also, while debugging, set the cronjob to run every minute (* * * * *)

نصائح أخرى

Basically the problem is the sudo command so we will allow sudo to run tar for the "user" without prompting for the password.

Add the following line in /etc/sudoers file.

user ALL=(ALL) NOPASSWD:/bin/tar

where user is the user installing the crontab.

I suspect a PATH problem, try to set some variables at the top of sudo crontab -e :

MAILTO=your_email@domain.tld # to get the output if there's errors
PATH=/usr/bin:/bin:/usr/local/bin:/usr/local/sbin:/sbin

You can write your command in a script like run.sh

#/bin/sh -l
tar -cvpzf backupfolder/localhost.tar.gz /var/www

then use the crontab to run the script.

IMPORTANT NOTE: the script's first line has the "-l" option. Try it.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top