重命名 cron 文件

重命名 cron 文件

重命名 /var/spool/cron/ 中的 cron 文件是否意味着 cron 文件的内容将不再执行?或者 /var/spool/cron/ 中的所有文件都将被执行,无论文件名是什么。

答案1

/var/spool/cron(或某些系统上的 /var/spool/cron/crontabs 或 /var/spool/cron/tabs)中的文件将以文件命名用户的权限运行。例如,/var/spool/cron/root 将以用户“root”的身份运行,而 /var/spool/cron/tom_13 将以用户“tom_13”的身份运行。

如果 crontab 文件被重命名为另一个有效用户,则它应该以该用户的身份运行。但是,有两个注意事项:

  1. 如果将 crontab 重命名为与有效用户不对应的文件名,我不知道预期的行为是什么。它可能以 root 身份运行,可能以拥有该文件的用户身份运行,或者可能根本不运行。
  2. 某些 cron 守护程序不会检查 /var/spool/cron 是否有更改,除非您使用命令进行更改crontab。如果您要手动进行更改,则可能需要重新启动 cron 守护程序以使更改生效。

查看 crontab ( ) 的手册页man 1 crontab以了解其工作原理。如果您使用的是 Vixie cron(目前大多数 Linux 发行版似乎都喜欢它),您可以执行以下操作让一个用户的 crontab 以另一个用户的身份运行(与重命名文件效果相同,但更安全):

  1. 将旧用户的 crontab 保存到文件中:crontab -u olduser -l > olduser.cron
  2. 将其导入到新用户的 crontab 中:crontab -u newuser olduser.cron
  3. 删除旧用户的crontab:crontab -u olduser -r

答案2

Cron 被压缩到 /etc/crontab,所有神奇的事情都发生在这里。实际上,默认情况下 crontab 只有一条类似于这样的记录:

-*/15 * * * *   root  test -x /usr/lib/cron/run-crons && /usr/lib/cron/run-crons >/dev/null 2>&1

如您所见,这将每 15 分钟执行一次 /usr/lib/cron/run-crons,而 run-crons 实际上是一个脚本。

简单看一下脚本,您将看到哪些目录应该保存 cron 脚本:

for CRONDIR in /etc/cron.{hourly,daily,weekly,monthly} ; do

深入挖掘并检查此脚本的内容,你会发现是的,它将执行所有脚本在适当的目录中:

for SCRIPT in $CRONDIR/* ; do
    test -d $SCRIPT && continue
    case "$SCRIPT" in
           .svn)           continue ;;
           *.rpm*)         continue ;;
           *.swap)         continue ;;
           *.bak)          continue ;;
           *.orig)         continue ;;
           \#*)            continue ;;
           *~)             continue ;;
    esac

... 除了提到的文件扩展名。因此,您只需在文件末尾添加“.bak”,这样 cron 就不会执行它。

注意:本文使用 OpenSUSE 编写,其他发行版可能会有所不同

答案3

如果您想阻止它运行,一种方法是编辑该用户的 crontab 并注释掉所有行:

sudo crontab -u username -e

并在没有 # 的每一行开头添加一个 # 。

答案4

cron 命令说明如下:

   Cron searches /var/spool/cron for crontab files which are named  after
   accounts  in /etc/passwd; crontabs found are loaded into memory. Cron
   also searches for /etc/crontab and the files in the /etc/cron.d direc-
   tory,  which  are  in  a different format (see crontab(5)).  Cron then
   wakes up every minute, examining all stored  crontabs,  checking  each
   command  to  see if it should be run in the current minute.  When exe-
   cuting commands, any output is mailed to the owner of the crontab  (or
   to  the  user named in the MAILTO environment variable in the crontab,
   if such exists).

   Additionally, cron checks each minute to see if its spool  directoryâs
   modtime  (or  the modtime on /etc/crontab) has changed, and if it has,
   cron will then examine the modtime on all crontabs  and  reload  those
   which  have  changed.   Thus  cron  need  not  be restarted whenever a
   crontab file is modified.  Note that the  Crontab(1)  command  updates
   the modtime of the spool directory whenever it changes a crontab.

因此,如果我正确理解了这一点,重命名为不存在的用户就可以了。

相关内容