문제
한 번에 A *NIX 시스템의 예정된 CRON 작업을 모두 볼 수있는 명령이나 기존 스크립트가 있습니까? 모든 사용자 크론 탭과 /etc/crontab
, 그리고 무엇이든 /etc/cron.d
. 또한 특정 명령이 실행되는 것을 보는 것도 좋을 것입니다. run-parts
안에 /etc/crontab
.
이상적으로는 좋은 열 형태의 출력을 원하고 의미있는 방식으로 주문합니다.
그런 다음 여러 서버 의이 목록을 병합하여 전체 "이벤트 일정"을 볼 수 있습니다.
나는 그런 대본을 직접 쓰려고했지만 누군가가 이미 문제에 빠졌다면 ...
해결책 2
나는 스크립트를 작성하게되었다 (나는 Bash 스크립팅의 더 좋은 점을 가르치려고 노력하고 있으므로 Perl과 같은 것을 보지 못한 이유). 그것은 단순한 일이 아니지만, 내가 필요한 대부분의 일을합니다. 개별 사용자의 크론 탭을 찾는 데 Kyle의 제안을 사용하지만 /etc/crontab
(시작된 스크립트 포함 run-parts
안에 /etc/cron.hourly
, /etc/cron.daily
, 등의 일자리 /etc/cron.d
예배 규칙서. 모든 것을 가져 와서 다음과 같은 디스플레이로 통합합니다.
mi h d m w user command
09,39 * * * * root [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 | xargs -r -0 rm
47 */8 * * * root rsync -axE --delete --ignore-errors / /mirror/ >/dev/null
17 1 * * * root /etc/cron.daily/apt
17 1 * * * root /etc/cron.daily/aptitude
17 1 * * * root /etc/cron.daily/find
17 1 * * * root /etc/cron.daily/logrotate
17 1 * * * root /etc/cron.daily/man-db
17 1 * * * root /etc/cron.daily/ntp
17 1 * * * root /etc/cron.daily/standard
17 1 * * * root /etc/cron.daily/sysklogd
27 2 * * 7 root /etc/cron.weekly/man-db
27 2 * * 7 root /etc/cron.weekly/sysklogd
13 3 * * * archiver /usr/local/bin/offsite-backup 2>&1
32 3 1 * * root /etc/cron.monthly/standard
36 4 * * * yukon /home/yukon/bin/do-daily-stuff
5 5 * * * archiver /usr/local/bin/update-logs >/dev/null
매일 일정을 볼 수 있도록 사용자와 시간 또는 분씩 더 많은 종류의 종류를 보여줍니다.
지금까지 우분투, 데비안, 레드 모자에서 테스트했습니다.
#!/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}"
다른 팁
이것을 루트로 실행해야하지만 :
for user in $(cut -f1 -d: /etc/passwd); do crontab -u $user -l; done
Crontab을 나열하는 각 사용자 이름을 루프합니다. Crontabs는 해당 사용자가 소유하고 있으므로 다른 사용자의 Crontab을 볼 수 없습니다.
편집하다Crontab이 속한 사용자를 알고 싶다면 사용하십시오. echo $user
for user in $(cut -f1 -d: /etc/passwd); do echo $user; crontab -u $user -l; done
Ubuntu 또는 Debian에서 Crontab을 볼 수 있습니다. /var/spool/cron/crontabs/
그런 다음 각 사용자의 파일이 있습니다. 물론 사용자 별 Crontab을위한 것입니다.
Redhat 6/7 및 Centos의 경우 Crontab이 아래에 있습니다. /var/spool/cron/
.
여기에는 모든 사용자의 모든 Crontab 항목이 표시됩니다.
sed 's/^\([^:]*\):.*$/crontab -u \1 -l 2>\&1/' /etc/passwd | grep -v "no crontab for" | sh
Linux 버전에 따라 다르지만 사용합니다.
tail -n 1000 /var/spool/cron/*
루트로. 매우 간단하고 매우 짧습니다.
다음과 같은 출력을 제공합니다.
==> /var/spool/cron/root <==
15 2 * * * /bla
==> /var/spool/cron/my_user <==
*/10 1 * * * /path/to/script
개선 된 출력 형식으로 Kyle Burton의 답변의 작은 개선 :
#!/bin/bash
for user in $(cut -f1 -d: /etc/passwd)
do echo $user && crontab -u $user -l
echo " "
done
getent passwd | cut -d: -f1 | perl -e'while(<>){chomp;$l = `crontab -u $_ -l 2>/dev/null`;print "$_\n$l\n" if $l}'
이것은 Passwd를 직접 엉망으로 만드는 것을 피하고 Cron 항목이없는 사용자를 건너 뛰고 사용자 이름과 크론 탭을 인쇄합니다.
대부분 여기에 이것을 떨어 뜨려서 다시 찾아야 할 경우 나중에 찾을 수 있습니다.
NIS를 사용하여 클러스터를 확인하면 Matt의 답변/var/spool/cron/탭에 따라 사용자가 Crontab 항목이 있는지 확인하는 유일한 방법.
grep -v "#" -R /var/spool/cron/tabs
이 스크립트는 Centos에서 환경의 모든 크론을 나열하는 데 도움이되었습니다.
sudo cat /etc/passwd | sed 's/^\([^:]*\):.*$/sudo crontab -u \1 -l 2>\&1/' | grep -v "no crontab for" | sh
위의 간단한 원 라이너 답변이 마음에 듭니다.
$ (cut -f1 -d : /etc /passwd)의 사용자의 경우; crontab -u $ user -l; 완료
그러나 -u 플래그가없고 확인중인 사용자를 인쇄하지 않는 Solaris는 다음과 같이 수정할 수 있습니다.
for user in $(cut -f1 -d: /etc/passwd); do echo User:$user; crontab -l $user 2>&1 | grep -v crontab; done
계정이 CRON 등을 사용할 수 없을 때 Crontab에서 발생한 오류가없는 사용자 목록을 얻게됩니다. Solaris에서는 역할도 /etc /passwd에있을 수 있습니다 ( /etc /user_attr 참조).
for user in $(cut -f1 -d: /etc/passwd);
do
echo $user; crontab -u $user -l;
done
루트 사용자로부터 목록을 얻으려면.
for user in $(cut -f1 -d: /etc/passwd); do echo $user; sudo crontab -u $user -l; done
다음은 댓글, 빈 줄 및 Crontab이없는 사용자의 오류를 제거합니다. 당신이 남긴 것은 명확한 사용자와 직무 목록입니다.
사용에 유의하십시오 sudo
두 번째 라인에서. 이미 뿌리를 내리면 제거하십시오.
for USER in $(cut -f1 -d: /etc/passwd); do \
USERTAB="$(sudo 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
예제 출력 :
# ------ root ------
0 */6 * * * /usr/local/bin/disk-space-notify.sh
45 3 * * * /opt/mysql-backups/mysql-backups.sh
5 7 * * * /usr/local/bin/certbot-auto renew --quiet --no-self-upgrade
# ------ sammy ------
55 * * * * wget -O - -q -t 1 https://www.example.com/cron.php > /dev/null
나는 이것을 Ubuntu (12 Thru 16)와 Red Hat (5 Thru 7)에서 사용합니다.
CRON 버전에 따라 다릅니다. freebsd에서 vixie cron을 사용하면 다음과 같은 일을 할 수 있습니다.
(cd /var/cron/tabs && grep -vH ^# *)
더 많은 탭 구분을 원한다면 다음과 같은 일을 할 수 있습니다.
(cd /var/cron/tabs && grep -vH ^# * | sed "s/:/ /")
SED 교체 부분의 문자 그대로 탭입니다.
사용자를 통해 루프하는 것이 더 많은 시스템 일 수 있습니다. /etc/passwd
그리고 그렇게 crontab -l -u $user
그들 각각에 대해.
이 매우 유용한 스크립트에 감사드립니다. 오래된 시스템 (문자열의 다른 egrep 및 탭을 처리하는 Red Hat Enterprise 3) 및 /etc/cron.d/에 아무것도없는 다른 시스템 (스크립트가 오류로 끝났음)에서 실행하는 작은 문제가있었습니다. 따라서 다음은 그러한 경우에 작동하는 패치가 있습니다.
2a3,4
> #See: http://stackoverflow.com/questions/134906/how-do-i-list-all-cron-jobs-for-all-users
>
27c29,30
< match=$(echo "${line}" | egrep -o 'run-parts (-{1,2}\S+ )*\S+')
---
> #match=$(echo "${line}" | egrep -o 'run-parts (-{1,2}\S+ )*\S+')
> match=$(echo "${line}" | egrep -o 'run-parts.*')
51c54,57
< cat "${CRONDIR}"/* | clean_cron_lines >>"${temp}" # */ <not a comment>
---
> sys_cron_num=$(ls /etc/cron.d | wc -l | awk '{print $1}')
> if [ "$sys_cron_num" != 0 ]; then
> cat "${CRONDIR}"/* | clean_cron_lines >>"${temp}" # */ <not a comment>
> fi
67c73
< sed "1i\mi\th\td\tm\tw\tuser\tcommand" |
---
> sed "1i\mi${tab}h${tab}d${tab}m${tab}w${tab}user${tab}command" |
나는 첫 번째 egrep의 변화가 좋은 생각인지 확실하지 않지만,이 스크립트는 아무런 문제없이 RHEL3,4,5 및 Debian5에서 테스트되었습니다. 도움이 되었기를 바랍니다!
@kyle 위에 건물
for user in $(tail -n +11 /etc/passwd | cut -f1 -d:); do echo $user; crontab -u $user -l; done
일반적으로 /etc /passwd의 상단에있는 주석을 피하기 위해
그리고 MacOSX에서
for user in $(dscl . -list /users | cut -f1 -d:); do echo $user; crontab -u $user -l; done
더 나은 하나의 라이너가 아래에있을 것이라고 생각합니다. 예를 들어 NIS 또는 LDAP에 사용자가있는 경우 /etc /passwd에 있지 않습니다. 이것은 로그인 한 모든 사용자의 크론 타브를 제공합니다.
for I in `lastlog | grep -v Never | cut -f1 -d' '`; do echo $I ; crontab -l -u $I ; done
모든 사용자 목록에 대해 작성할 수 있습니다.
sudo crontab -u userName -l
,
당신은 또한 갈 수도 있습니다
cd /etc/cron.daily/
ls -l
cat filename
이 파일에는 일정이 나열됩니다
cd /etc/cron.d/
ls -l
cat filename
사과와 유콘 데드에게 감사합니다.
나는 완벽한 일이 아니지만 쉽게 읽을 수있는 타이밍 설정을 요약하려고 노력했지만 '매주 금요일'또는 '월요일에만'만지지 않습니다.
이것은 버전 10입니다 - 지금 :
- 훨씬 더 빨리 실행됩니다
- 선택적인 진행 문자가 있으므로 속도를 더욱 향상시킬 수 있습니다.
- 분배기 라인을 사용하여 헤더와 출력을 분리합니다.
- 모든 타이밍 간격 Uncountered를 요약 할 수있는 소형 형식의 출력.
- Jan ... DEC 디스크립터를 수개월 동안 수락합니다
- 주일에 몬 ... 태양 디스크립터를 수락합니다
- Debian 스타일의 Dummying in Anacron이 누락되었을 때 처리하려고합니다.
- [-x ...]를 사용하여 사전 테스트 실행 가능성 후 파일을 실행하는 Crontab 라인을 처리하려고합니다.
- "명령 -v"를 사용하여 사전 테스트 실행 가능성 후 파일을 실행하는 Crontab 라인을 처리하려고합니다.
- 간격 스팬 및 목록을 사용할 수 있습니다.
- 사용자 별 /var /spool crontab 파일에서 런-파트 사용을 지원합니다.
나는 지금 여기에 대본을 게시하고 있습니다.
https://gist.github.com/myshkin-uk/d667116d3e2d689f23f18f6cd3c71107
파일을 통해 반복하는 문제이므로 (/etc/passwd
) 그리고 행동을 수행하면서, 나는 적절한 접근 방식을 놓치고 있습니다. 파일 (데이터 스트림, 변수) 라인별 라인 (및/또는 필드 별 필드)을 어떻게 읽을 수 있습니까?:
while IFS=":" read -r user _
do
echo "crontab for user ${user}:"
crontab -u "$user" -l
done < /etc/passwd
이것은 읽습니다 /etc/passwd
라인별로 라인을 사용합니다 :
현장 분리기로. 말함으로써 read -r user _
, 우리는 만든다 $user
첫 번째 필드를 잡고 _
나머지 (필드를 무시하는 정크 변수).
이런 식으로 우리는 전화 할 수 있습니다 crontab -u
변수를 사용합니다 $user
, 우리는 안전에 대해 인용합니다 (공백이 포함되어 있으면 어떻게해야합니까? 그러한 파일에는 거의 없지만 알 수 없습니다).
SOLARIS에서 특정 알려진 사용자 이름 :
crontab -l username
다른 모든 *닉스는 필요합니다 -u
수정 자 :
crontab -u username -l
Solaris에서 모든 사용자의 작업을 한 번에 얻으려면 위의 다른 게시물과 마찬가지로 다음과 같습니다.
for user in $(cut -f1 -d: /etc/passwd); do crontab -l $user 2>/dev/null; done
/var/spool/cron/crontabs를 보면 가장 좋은 방법입니다.
이 스크립트는 Crontab을 파일로 출력하고 Crontab 항목이없는 사람을 확인하는 모든 사용자가 나와 있습니다.
for user in $(cut -f1 -d: /etc/passwd); do
echo $user >> crontab.bak
echo "" >> crontab.bak
crontab -u $user -l >> crontab.bak 2>> > crontab.bak
done