Не работает crontab linux

Why is my Crontab not working, and how can I troubleshoot it?

We all know that Cron or Crontab works as the best job scheduler for the Linux-based system. Whenever you wish to run certain time-bound operations, you can always take the services of the Cron daemon. However, at times, your Crontab might stop working, and you might wonder why? Also, in such situations, you are willing to try out all the possible ways to fix this issue. Therefore, we have dedicated today’s article to the issues that cause a hindrance in the proper working of the Crontab and how they can be troubleshot.

Why is my Crontab not working?

Certain reasons can cause your Crontab to fail. The first and foremost one is that your Cron daemon might not be working for some reason which will consequently cause your Crontab to fail. The environment variables of your system might not have been properly set up. There can be some errors in the script that you are trying to execute with your Crontab. For example, the desired script might be missing Shebang, i.e., the necessary character sequence at the start of the script. The script you are trying to execute with Crontab might not be executable, i.e., its permissions are restricted. The path of the script that you are trying to execute might be incorrect. You might be missing out on the extension of the file that you are trying to execute with Crontab.

How can I Troubleshoot my Faulty Crontab?

Depending upon the actual cause of the Crontab failure, there are different ways to perform troubleshooting. Some of these ways are listed below:

First, you need to ensure that the Cron daemon is active and running in the background. This can be done simply by checking its status with the following command:

Check the path of the command or the file that you are trying to execute with Crontab and ensure if it is correct.

Ensure that you have provided the exact name of the file or the command you are trying to execute. Moreover, it would be best to make sure that the file or script you are trying to execute has the relevant permissions set up.

Читайте также:  Стандартные пароли kali linux

If you want to write Cron jobs for the current user, then you must access the Crontab file of the current user with the command shown below:

If you write the “sudo” keyword before this command, it will open up the root user’s Crontab file, and the jobs you will write in it will not be executed for the current user; rather, they will be executed for the root user. This thing should especially be taken care of while writing Cron jobs.

Try running your desired script through the terminal to figure out if there are some issues with your script or fail only because of Crontab.

Also, make sure not to skip Shebang while creating your scripts.

Check the Crontab logs with the following command to troubleshoot for errors:

Ensure that the syntax of the Cron job that you have listed in your Crontab file is correct.

Make sure to provide the relevant file extensions while executing them as Cron jobs.

Conclusion:

In this article, we did an open-ended discussion on the various issues that can cause your Crontab to fail. After digging deeper into those causes, we shared with you some of the most common and quick methods of troubleshooting these issues for fixing your Crontab immediately.

About the author

Karim Buzdar

Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. He blogs at LinuxWays.

Источник

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:

Читайте также:  Device ids in linux

# 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_-]+$).

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.

Читайте также:  Installing deb on arch linux

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

Источник

Почему мой Crontab не работает и как его устранить?

Главное меню » Почему мой Crontab не работает и как его устранить?

Почему мой Crontab не работает и как его устранить?

В се мы знаем, что Cron или Crontab работают как лучший планировщик заданий для системы на базе Linux. Всякий раз, когда вы хотите выполнить определенные операции с ограничением по времени, вы всегда можете воспользоваться услугами демона Cron. Однако иногда ваш Crontab может перестать работать, и вы можете задаться вопросом, почему? Кроме того, в таких ситуациях вы готовы попробовать все возможные способы решения этой проблемы. Поэтому мы посвятили сегодняшнюю статью проблемам, которые мешают правильной работе Crontab, и способам их устранения.

Почему мой Crontab не работает?

Определенные причины могут привести к сбою вашего Crontab. Первая и самая главная проблема заключается в том, что ваш демон Cron может не работать по какой-либо причине, что, следовательно, приведет к сбою вашего Crontab. Возможно, переменные среды вашей системы настроены неправильно. В скрипте, который вы пытаетесь выполнить с помощью Crontab, могут быть ошибки. Например, в желаемом сценарии может отсутствовать Shebang, т. е. необходимая последовательность символов в начале сценария. Сценарий, который вы пытаетесь выполнить с помощью Crontab, может быть не исполняемым, т. е. его права доступа ограничены. Возможно, путь к сценарию, который вы пытаетесь выполнить, неверен. Возможно, вам не хватает расширения файла, который вы пытаетесь запустить с помощью Crontab.

Как я могу устранить неисправность моего неисправного Crontab?

В зависимости от фактической причины сбоя Crontab существуют разные способы устранения неполадок. Некоторые из этих способов перечислены ниже:

    Во-первых, вам нужно убедиться, что демон Cron активен и работает в фоновом режиме. Это можно сделать, просто проверив его статус с помощью следующей команды:

$ sudo systemctl status cron

Заключение:

В этой статье мы провели открытое обсуждение различных проблем, которые могут привести к сбою вашего Crontab. После более глубокого изучения этих причин мы поделились с вами некоторыми из наиболее распространенных и быстрых методов устранения этих проблем для немедленного исправления вашего Crontab.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Источник

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