Linux cron не работает

Top 5 reasons your crontab scripts are not working

Crontab (cron table) is a configuration file that specifies shell commands to run periodically on a given schedule. It is commonly used to automate system maintenance or administration. Crontab is available in almost Linux distribution and easy to use.

Why crontab scripts are not working?

There are several reasons for that. Following is top 5 reason we might have

1. Crontab software is not installed

Although Crontab is available in almost Linux distribution by default today, there is customized version of Linux that misses cron package. To install cron…

If you Linux distribution doesn’t have package manager, you can install cronie from its source code.

2. Your cron service is not running

The cron scripts are called and executed on a given schedule by a crontab daemon software. If your cron service isn’t running for some reason, your scripts will not be execute. To start cron service:

# On RHEL based systems, use
$ sudo service crond start

# Or using systemd
$ sudo systemctl start crond

# Debian based systems, use
$ sudo service cron start

# Or using systemd
$ sudo systemctl start cron

Also make sure the cron service will start on boot.

# On RHEL based systems , use
$ sudo chkconfig crond on
# Or using systemd
$ sudo systemctl enable crond

# On Debian based systems, use
$ sudo update-rc.d cron defaults
# Or using systemd
$ sudo systemctl enable cron

3. Your cron script has a bad file name

Cron service supports to run external scripts which put in cron.d , cron.daily , cron.hourly , cron.monthly and cron.weekly directories. According to RUN-PARTS(8), your script filenames must follow these rules:

If neither the –lsbsysinit option nor the –regex option is given then the names must consist entirely of ASCII upper- and lower-case letters, ASCII digits, ASCII underscores, and ASCII minus-hyphens.

If the –lsbsysinit option is given, then the names must not end in .dpkg-old or .dpkg-dist or .dpkg-new or .dpkg-tmp, and must belong to one or more of the following namespaces: the LANANA-assigned namespace (^[a-z0-9]+$); the LSB hierarchical and reserved namespaces (^?([a-z0-9.]+-)+[a-z0-9]+$); and the Debian cron script namespace (^[a-zA-Z0-9_-]+$).

Читайте также:  Linux mint 11 росинка установка

If the –regex option is given, the names must match the custom extended regular expression specified as that option’s argument.

A common naming issue i usually see is using the dot character in the filename as we want to specify the file extension when saving a script. This dot character breaks the rule and make cron service ignore your script. If you have any scripts like backup.sh , you should rename it to backup .

4. Your cron script has bad permission

The script must be executable so your cron service can run it. To give executable permission to your script, you can use chmod command. For example:

$ sudo chmod +x /etc/cron.hourly/backup
$ grep -i cron /var/log/syslog
2018-01-06T03:47:49.283841+01:00 ubuntu cron[43561]: (user) INSECURE MODE (mode 0600 expected) (crontabs/user)
$ sudo chmod 600 /etc/cron.hourly/backup

5. Your cron script cannot be executed properly

There are several reasons for this. Let’s see some common cases below

Shebang

In most of the cases, we should use shebang at the start of the script. For example, if your script is written in Bash, try to use #!/bin/bash , in Python use #!/usr/bin/env python , etc. This allow scripts and data files to be used as commands, hiding the details of their implementation from users and other programs, by removing the need to prefix scripts with their interpreter on the command line.

Missing environment variables

Another common issue is related to the environment variable. You tested your script by excuting it from the command line and it worked as expected but somehow it didn’t work in crontab. To troubleshoot, you can log the actual environment variables that loaded in the cron by having this simple command in cron table.

If you are using crontab -e to write cron commands, you might want to load the environment variables that needed by your scripts / applications. These variables can be loaded directly by putting right before the command, for example:

0 10 * * * MY_ENV_VAR=my_value my_command my_parameters
0 10 * * * . $HOME/.my_vars; my_command my_parameters

Or if those variables are loaded under your user profile, let’s say bash profile for example. You can specify the shell at the begining of crontab.

SHELL=/bin/bash

0 10 * * * my_command my_parameters

Источник

Почему не запускается cron скрипт?

Помогите неопытному. Операционная система CentOS 6.3. Пытаюсь настроить бэкап папки и базы данных через rsync. Скрипты через консоль запускаются нормально, все работает, крон ошибок при сохранении не выдает, просто пишет «installing new crontab». Если я все правильно понимаю, то вроде все правильно. Но почему-то ничего не работает. Права на папку где лежат скрипты 777.

#!/bin/bash cd /mnt/backup/neon_backup/MySQL_backup mysqldump -u root -pnppwd --all-databases > mysql_backup.sql tar cvjf back_mysql.tar.bz2 mysql_backup.sql
#!/bin/bash sudo rsync --archive /home/share --delete /mnt/backup/neon_backup sudo rsync --archive /var/www/html/vtgr --delete /mnt/backup/neon_backup
#!/bin/bash sudo rsync --archive /var/www/html/vtgr --delete /mnt/backup/neon_backup/vtgr_weekly cd /mnt/backup/neon_backup/vtgr_weekly/MySQL_weekly mysqldump -u root -pnppwd --all-databases > mysql_backup.sql tar cvjf back_mysql.tar.bz2 mysql_backup.sql
0 1 * * * /bin/bash /usr/share/script.sh 0 2 * * * /bin/bash /usr/share/script2.sh * * * * 1 /bin/bash /usr/share/script3.sh 30 4 * * * /var/www/vtgr/script/updateControlWorker.php 30 4 * * * /var/www/vtgr/script/createTack.php

Я уже по всякому попробовал и /bin/bash в crontab убирал, поскольку как я прочитал, если в начале скрипта стоит #!/bin/bash , то это не нужно.

Читайте также:  Linux применить настройки сети

Простой 1 комментарий

gluck59

Indermove

Все нашел ответ на свой вопрос:

1) Кронтаб нужно запускать так: sudo crontab -e — это нужно чтобы cron запускал скрипты из под root.
2) Инструкции для cron должны быть такими. Нужно обязательно писать bash перед указанием пути к скрипту. После указания пути к скрипту дописать >/dev/null 2>&1
Пример:

0 1 * * * bash /bin/bash /usr/share/script.sh >/dev/null 2>&1 0 2 * * * bash /bin/bash /usr/share/script2.sh >/dev/null 2>&1 * * * * 1 bash /bin/bash /usr/share/script3.sh >/dev/null 2>&1
#!/bin/bash rsync --archive /home/share --delete /mnt/backup/neon_backup rsync --archive /var/www/html/vtgr --delete /mnt/backup/neon_backup

3) Сами скрипты действительно должны быть лишены sudo, так как и так запускаются из под пользователя root.
Пример:

#!/bin/bash cd /mnt/backup/neon_backup/MySQL_backup mysqldump -u root -pnppwd --all-databases > mysql_backup.sql set > /tmp/script-environment tar cvjf back_mysql.tar.bz2 mysql_backup.sql

egor_nullptr

Всё дело в sudo, не используйте его в скриптах если не настроено выполнение без ввода пароля. Если требуется выполнение от root-а, то перенесите задачи крона в root-ый крон.

Indermove

egor_nullptr

crontab -l > /tmp/tmp_crontab && sudo crontab -f /tmp/tmp_crontab

Indermove

Indermove

1. /bin/bash в crontab не нужен. Выкиньте его и сделайте скрипты исполняемыми.
2. приложения из cron запускаются с минимальным environment, если mysqldump не лежит в /bin или /usr/bin, script.sh его не найдёт. Добавьте в скрипт set > /tmp/script-environment чтобы посмотреть, с чем они запускаются.
3. sudo — нужен nopasswd

iamy

Можете объяснить что значит: >/dev/null 2>&1
У меня прописано сейчас вот так:
00 16,18,20,22 * * * garanty /home/garanty/www/garancy.finexpert.pro/ftpset.sh 2>/home/garanty/www/garancy.finexpert.pro/tmp/logscron.txt

Не запускается, хотя в логах пишет, что все нормально.

2>/home/garanty/www/garancy.finexpert.pro/tmp/logscron.txt — эта штука должна записывать в файл logscron.txt ошибки если они будут?

> Можете объяснить что значит: >/dev/null 2>&1
stdout — в /dev/null, stderr — туда же, куда stdout

> 2>/home/garanty/www/garancy.finexpert.pro/tmp/logscron.txt — эта штука должна записывать в файл logscron.txt ошибки если они будут?
да, ошибки выводимые garanty

1. Избавьтесь от sudo. Выполняйте крон от того пользователя у которого есть права без sudo.
2. Посмотрите логи крона.

Indermove

Это лог крона. Если я правильно понял, то все выполняется. Так?
Dec 18 21:00:01 server-centos CROND[7100]: (root) CMD (/usr/share/script.sh)
Dec 18 21:00:01 server-centos CROND[7101]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:01:01 server-centos CROND[7111]: (root) CMD (run-parts /etc/cron.hourly)
Dec 18 21:01:01 server-centos run-parts(/etc/cron.hourly)[7111]: starting 0anacron
Dec 18 21:01:01 server-centos CROND[7112]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:01:01 server-centos run-parts(/etc/cron.hourly)[7122]: finished 0anacron
Dec 18 21:02:01 server-centos CROND[7126]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:03:01 server-centos CROND[7132]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:04:01 server-centos CROND[7137]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:05:01 server-centos CROND[7142]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:06:01 server-centos CROND[7148]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:07:01 server-centos CROND[7153]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:08:01 server-centos CROND[7159]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:09:01 server-centos CROND[7166]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:10:01 server-centos CROND[7172]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:11:01 server-centos CROND[7178]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:12:01 server-centos CROND[7185]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:13:01 server-centos CROND[7190]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:14:01 server-centos CROND[7195]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:15:01 server-centos CROND[7202]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:15:01 server-centos CROND[7203]: (server) CMD (/usr/share/script.sh)
Dec 18 21:15:01 server-centos CROND[7205]: (root) CMD (/usr/share/script.sh)
Dec 18 21:16:01 server-centos CROND[7215]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:17:01 server-centos CROND[7220]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:18:01 server-centos CROND[7225]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:19:01 server-centos CROND[7232]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:20:01 server-centos CROND[7237]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:21:01 server-centos CROND[7243]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:22:01 server-centos CROND[7248]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:23:01 server-centos CROND[7253]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:24:01 server-centos CROND[7259]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:25:01 server-centos CROND[7264]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:26:01 server-centos CROND[7270]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:27:01 server-centos CROND[7275]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:28:01 server-centos CROND[7280]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:29:01 server-centos CROND[7299]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:30:01 server-centos CROND[7325]: (root) CMD (/usr/share/script.sh)
Dec 18 21:30:01 server-centos CROND[7326]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:31:01 server-centos CROND[7355]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:32:01 server-centos CROND[7380]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:33:01 server-centos CROND[7405]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:34:01 server-centos CROND[7430]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:35:01 server-centos CROND[7455]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:36:01 server-centos CROND[7481]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:37:01 server-centos CROND[7506]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:38:01 server-centos CROND[7531]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:39:01 server-centos CROND[7556]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:40:01 server-centos CROND[7581]: (root) CMD (/usr/share/script3.sh)
Dec 18 21:41:01 server-centos CROND[7607]: (root) CMD (/usr/share/script3.sh)

Читайте также:  Default directory permissions in linux

Источник

Оцените статью
Adblock
detector