Показать cron job-ы по всем пользователям в Unix/Linux
Некоторые статьи, я беру из черновиков (которые создавал года 2-3 назад) и привожу до ума. И сейчас я, хотел бы рассказать как можно получить все крон-задачи для всех пользователей в Unix/Linux ОС.
Самое первое что приходит на ум, это получить список пользователей в passwd:
# for user in $(cut -f1 -d: /etc/passwd); do echo $user; crontab -u $user -l; done
Вот пример вывода:
root # .---------------- minute (0 - 59) # | .------------- hour (0 - 23) # | | .---------- day of month (1 - 31) # | | | .------- month (1 - 12) OR jan,feb,mar,apr ... # | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat # | | | | | # * * * * * user-name command to be executed # # minute hour mday month day who command # 0 0 */3 * * /usr/bin/bash /home/scripts/backUPs.sh # bin no crontab for bin daemon no crontab for daemon adm no crontab for adm
Приведу другую вариацию такого вывода, например:
# sed 's/^\([^:]*\):.*$/crontab -u \1 -l 2>\&1/' /etc/passwd | grep -v "no crontab for" | sh
Данный пример рабочий, но он будет показывать много не нужного. Давайте немного доработает и приведем к следующему виду:
# for user in $(cut -f1 -d: /etc/passwd); do crontab -u $user -l 2>/dev/null | grep -v '^#'; done
Получим вывод:
0 0 */3 * * /usr/bin/bash /home/scripts/backUPs.sh
Вот, так уже лучше и не выводит хлам.
Приведу другую вариацию такого вывода, например:
# getent passwd | cut -d: -f1 | perl -e'while(<>){chomp;$l = `crontab -u $_ -l 2>/dev/null`;print "$_\n$l\n" if $l}'
Или еще другой пример:
for USER in $(cut -f1 -d: /etc/passwd); do \ USERTAB="$(crontab -u "$USER" -l 2>&1)"; \ FILTERED="$(echo "$USERTAB"| grep -vE '^#|^$|no crontab for|cannot use this program')"; \ if ! test -z "$FILTERED"; then \ echo "# ------ $(tput bold)$USER$(tput sgr0) ------"; \ echo "$FILTERED"; \ echo ""; \ fi; \ done
Выглядит очень хорошо и наглядно!
Нашел готовое решение в виде скрипта, вот его содержание:
#!/bin/bash
# System-wide crontab file and cron job directory. Change these for your system.
CRONTAB='/etc/crontab'
CRONDIR='/etc/cron.d'
# Single tab character. Annoyingly necessary.
tab=$(echo -en "\t")
# Given a stream of crontab lines, exclude non-cron job lines, replace
# whitespace characters with a single space, and remove any spaces from the
# beginning of each line.
function clean_cron_lines() {
while read line ; do
echo "${line}" |
egrep --invert-match '^($|\s*#|\s*[[:alnum:]_]+=)' |
sed --regexp-extended "s/\s+/ /g" |
sed --regexp-extended "s/^ //"
done;
}
# Given a stream of cleaned crontab lines, echo any that don't include the
# run-parts command, and for those that do, show each job file in the run-parts
# directory as if it were scheduled explicitly.
function lookup_run_parts() {
while read line ; do
match=$(echo "${line}" | egrep -o 'run-parts (-{1,2}\S+ )*\S+')
if [[ -z "${match}" ]] ; then
echo "${line}"
else
cron_fields=$(echo "${line}" | cut -f1-6 -d' ')
cron_job_dir=$(echo "${match}" | awk '{print $NF}')
if [[ -d "${cron_job_dir}" ]] ; then
for cron_job_file in "${cron_job_dir}"/* ; do # */ <not a comment>
[[ -f "${cron_job_file}" ]] && echo "${cron_fields} ${cron_job_file}"
done
fi
fi
done;
}
# Temporary file for crontab lines.
temp=$(mktemp) || exit 1
# Add all of the jobs from the system-wide crontab file.
cat "${CRONTAB}" | clean_cron_lines | lookup_run_parts >"${temp}"
# Add all of the jobs from the system-wide cron directory.
cat "${CRONDIR}"/* | clean_cron_lines >>"${temp}" # */ <not a comment>
# Add each user's crontab (if it exists). Insert the user's name between the
# five time fields and the command.
while read user ; do
crontab -l -u "${user}" 2>/dev/null |
clean_cron_lines |
sed --regexp-extended "s/^((\S+ +){5})(.+)$/\1${user} \3/" >>"${temp}"
done < <(cut --fields=1 --delimiter=: /etc/passwd)
# Output the collected crontab lines. Replace the single spaces between the
# fields with tab characters, sort the lines by hour and minute, insert the
# header line, and format the results as a table.
cat "${temp}" |
sed --regexp-extended "s/^(\S+) +(\S+) +(\S+) +(\S+) +(\S+) +(\S+) +(.*)$/\1\t\2\t\3\t\4\t\5\t\6\t\7/" |
sort --numeric-sort --field-separator="${tab}" --key=2,1 |
sed "1i\mi\th\td\tm\tw\tuser\tcommand" |
column -s"${tab}" -t
rm --force "${temp}"
Запускаем скрипт:
# bash script_name.sh
Тестировался на rpm’s и deb’s ОС.
Если у вас Mac OS X:
$ for user in $(dscl . -list /users | cut -f1 -d:); do echo $user; sudo crontab -u $user -l; done
Вот и все, статья «Показать cron job-ы по всем пользователям в Unix/Linux» завершена.