Linux all users crontab

As root, how can I list the crontabs for all users?

I have a script being run automatically that I can’t find in the crontab for the expected users, so I’d like to search all users’ crontabs for it. Essentially I want to run a crontab -l for all users.

6 Answers 6

Well depends on the script but easily you can find your crontab as root with

Or you can find crontab from spool where is located file for all users

To show all users’ crontabs with the username printed at the beginning of each line:

cd /var/spool/cron/crontabs/ && grep . * 

One liner which lists all users and prints cron for every user:

for user in $(getent passwd | cut -f1 -d: ); do echo $user; crontab -u $user -l; done 
  • Doesn’t require knowing a system specific crontab path (e.g. /var/spool/cron/crontabs/ vs /var/spool/cron/
  • Won’t list «orphan» crons, i.e. crons for users that don’t exist anymore (and thus are not executed effectively)
for USER in `cat /etc/passwd | awk -F ":" ''` do echo "this crontab for user : $USER" crontab -u $USER -l 2>&1 done >> list_all_cron 

Strange need to escape chars on this web site. I think copy paste won’t work

Well you got the point : loop all users from /etc/passwd + awk and ask for crontab with crontab -u -l

Welcome to the site, and thank you for your contribution. Indeed the backtick is used for in-line comment formatting, making it difficult to use. Still, please note that the backtick format is deprecated anyway for command substitutions, and the $( . ) format should be used instead. Also, you don’t really need to cat a file into awk , just give the file to be read as parameter after the command.

Источник

How to List, Display, & View all Current Cron Jobs in Linux

Cron is a Linux utility for scheduling scripts and commands. This guide will show you several options to view current cron jobs scheduled in the crontab list.

how to display cron jobs in linux

Listing Cron Jobs in Linux

How to List all Active Cron Jobs Running

To list all scheduled cron jobs for the current user, enter:

list all scheduled cron jobs

Cron jobs are typically located in the spool directories. They are stored in tables called crontabs. You can find them in /var/spool/cron/crontabs. The tables contain the cron jobs for all users, except the root user.

Читайте также:  Конвейер команд linux создать файл

The root user can use the crontab for the whole system.

To display contents of the root user’s crontab, use the less command:

The system returns an output like the following:

# /etc/crontab: system-wide crontab # Unlike any other crontab you don't have to run the `crontab' # command to install the new version when you edit this file # and files in /etc/cron.d. These files also have username fields, # that none of the other crontabs do. SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin # m h dom mon dow user command 17 * * * * root cd / && run-parts --report /etc/cron.hourly 25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily ) 47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly ) 52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )

The /etc/crontab file can be edited using a text editor like nano:

In RedHat-based systems, this file is located at /etc/cron.d.

The /etc/ directory has additional cron subdirectories to organize hourly, daily, weekly, and monthly tasks. The ls (list) command displays files and directories. Use the -la option to list all entries in long format.

View Cron Jobs by User

To list cron jobs that belong to a specific user, run the following command:

sudo crontab -u [username] -l

Replace [username] with the actual username you’re viewing.

How to List Hourly Cron Jobs

To list hourly cron jobs enter the following in the terminal window:

The output should appear similar to this:

output of list hourly cron jobs

How to List Daily Cron Jobs

To list daily cron jobs, enter the command:

The results will look similar to the following output:

a listing of daily cron jobs currently running

How to Display Weekly Cron Jobs

To display weekly cron jobs:

The results will look something like the following:

total 28 drwxr-xr-x 2 root root 4096 Apr 24 20:46 . drwxr-xr-x 96 root root 4096 May 19 17:12 .. -rw-r--r-- 1 root root 102 Feb 9 2013 .placeholder -rwxr-xr-x 1 root root 730 Feb 23 2014 apt-xapian-index -rwxr-xr-x 1 root root 427 Apr 16 2014 fstrim -rwxr-xr-x 1 root root 771 Sep 23 2014 man-db -rwxr-xr-x 1 root root 211 Mar 27 2017 update-notifier-common

How to List Monthly Cron Jobs

To display monthly cron jobs use the ls command in this format:

total 12 drwxr-xr-x 2 root root 4096 Apr 24 20:44 . drwxr-xr-x 96 root root 4096 May 19 17:12 .. -rw-r--r-- 1 root root 102 Feb 9 2013 .placeholder

View Software Specific Cron Jobs

To view software specefic cron tasks, start by viewing a list of cron tasks:

Use the cat command to display the contents of update-notifier-common :

The results will look similar to:

#!/bin/sh set -e [ -x /usr/lib/update-notifier/package-data-downloader ] || exit 0 # Try to rerun any package data downloads that failed at package install time. /usr/lib/update-notifier/package-data-downloader

Note: You should also learn more about Linux at command, another useful tool for scheduling jobs.

Читайте также:  Создать сетевую папку линукс

Now you know how to navigate through the cron jobs on your machine. Cron is a helpful utility for scheduling tasks such as running a job at reboot. Use the commands from this guide to sort and display tasks scheduled through the cron tool.

Источник

2 Ноя 2017 12:11:58 | 4 комментария

Как получить список всех задач cron у всех пользователей в Linux ?

Вроде простая задача и вроде есть простое решение в виде:

for user in $(cut -d':' -f1 /etc/passwd); do crontab -u $user -l; done

Но решение неудобное и нужно всегда держать его в голове.
Давайте его усовершенствуем.

Исходные данные: Debian 8.9 (jessie)

Небольшой экскурс для тех кто не в курсе как вообще посмотреть список запланированных задач в планировщике cron в Linux:

Список задач у текущего пользователя:

Список задач у пользователя vasua:

Для вывод задач для всех пользователей очевидно нужно взять список пользователей в системе из /etc/passwd и сделать для каждого пользователя crontab -u USERNAME -l, то есть:

for user in $(cut -d':' -f1 /etc/passwd); do crontab -u $user -l; done

Недостаток этого решения очевиден:
1. Нужно всегда помнить эту команду.
2. Если у пользователя нет задач в планировщике то мы получим сообщение «no crontab for vasua» и таких сообщений может быть десятки если у вас много пользователей — это неудобно.
3. Вывод информации неудобно читать.

Но это не финишная прямая, а только начало, ведь опытный системный администратор знает, что кроме вывода списка заданий командой crontab -l -u USER есть еще задания планировщика в каталоге /etc/cron.d/ и это тоже нужно учитывать, потому что например панель хостинга SHELL=’/bin/sh’ */2 * * * * web30 /usr/bin/php -f /var/www/mysite.ru/web/yii cron-origin/index

Задачи в /etc/cron.d мы тоже учтем и покажем в решении ниже.

Итак, создадим функцию allcrontab в файле ~/.bashrc для ввода информации в более удобном виде:

# Определим цвета вывода red='\e[0;31m' RED='\e[1;31m' green='\e[0;32m' GREEN='\e[1;32m' NC='\e[0m' # Определим нашу функцию вывода списка всех задач cron у всех пользователей function allcrontab() < for user in $(cut -d':' -f1 /etc/passwd); do usercrontab=$(crontab -l -u $2>/dev/null) if [ -n "$" ]; then echo -e "$====== Start crontab for user $$$$ $======$" crontab -l -u $ | sed '/ *#/d; /^ *$/d' echo -e "$====== End crontab for user $$$$ $========$\n" fi done for crond in $(ls -L1 /etc/cron.d); do crondtab=$(cat "/etc/cron.d/$" 2>/dev/null | egrep -Ev "^\s*(;|#|$)") if [ -n "$" ]; then echo -e "$====== Start cron.d $$/etc/cron.d/$$ $======$" echo "$" echo -e "$====== End cron.d $$/etc/cron.d$$ $======$\n" fi done >

Выполняем source ~/.bashrc или перелогиниваемся и выполняем в консоле allcrontab и видим красивый вывод списка всех задач cron у всех пользователей и дополнительно вывод задач из /etc/cron.d:

Читайте также:  Добавить панель linux mint

Результат выполнения allcrontab

Результат выполнения allcrontab

Так же опытный системный администратор знает, что существует связаться со мной разными доступными способами.

Источник

How can get a list of all scheduled cron jobs on my machine?

My sysadmin has set up a bunch of cron jobs on my machine. I’d like to know exactly what is scheduled for what time. How can I get that list?

This isn’t the answer to the question, but just a note on best practices. One can configure these as per-user cron jobs for root or apache or whatever, but one should use /etc/crontab or (better, in most distros) /etc/cron.d and /etc/cron.[timeframe] .

I have posted a script which automates this to a useful degree at: — stackoverflow.com/questions/134906/… It’s not perfect but probably covers 90% of the needs. It is a good example of what not to write in bash.

4 Answers 4

With most Crons (e.g. Vixie-Cron — Debian/Ubuntu default, Cronie — Fedora default, Solaris Cron . ) you get the list of scheduled cron jobs for the current user via:

To get the crontabs for all users you can loop over all users and call this command.

Alternatively, you can look up the spool files. Usually, they are are saved under /var/spool/cron , e.g. for vcron following directory

contains all the configured crontabs of all users — except the root user who is also able to configure jobs via the system-wide crontab, which is located at

With cronie (default on Fedora/CentOS), there is a .d style config directory for system cron jobs, as well:

(As always, the .d directory simplifies maintaining configuration entries that are part of different packages.)

For convenience, most distributions also provide a directories where linked/stored scripts are periodically executed, e.g.:

/etc/cron.daily /etc/cron.hourly /etc/cron.monthly /etc/cron.weekly 

The timely execution of those scripts is usually managed via run-parts entries in the system crontab or via anacron.

With Systemd (e.g. on Fedora, CentOS 7, . ) periodic job execution can additionally be configured via timer units. The enabled system timers can be displayed via:

Note that users beside root may have user systemd instances running where timers are configured, as well. For example, on Fedora, by default, a user systemd instance is started for each user that is currently logged in. They can be recognized via:

$ ps aux | grep 'systemd[ ]--user' 

Those user timers can be listed via:

$ systemctl --user list-timers 

An alternative to issuing the list-timers command is to search for timer unit files (pattern: *.timer ) and symbolic links to them in the usual system and user systemd config directories:

$ find /usr/lib/systemd/ /etc/systemd -name '*.timer' $ find /home '(' -path '/home/*/.local/share/systemd/user/*' \ -o -path '/home/*/.config/systemd/*' ')' \ -name '*.timer' 2> /dev/null 

(As with normal service units, a timer unit is enabled via creating a symbolic link in the right systemd config directory.)

Источник

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