python-crontab:查找现有的 cron 作业给出了错误的结果



使用下面的python脚本,我想检查我的linux(centOS 7.5(服务器中是否定义了cron作业,如果不存在,我将使用python-crontab模块添加一个。它运行良好,直到我给 CRONTAB -R 删除现有的 cron 作业,当我重新执行我的 python 脚本时,它说 cronjob 存在,即使使用 crontab -r 删除它们。

import os
from crontab import CronTab
cron = CronTab(user="ansible")
job = cron.new(command='echo hello_world')
job.minute.every(1)
basic_command = "* * * * * echo hello_world"
basic_iter = cron.find_command("hello_world")
for item in basic_iter:
if str(item) == basic_command:
print("crontab job already exist", item)
break
else:
job.enable()
cron.write()
print("cronjob does not exist and added successfully.. please see "crontab -l" ")
break

当前 cron 作业列表

[ansible@node1 ansible]$ crontab -l
no crontab for ansible

[用户 - 安斯布尔]

python code results:

crontab job already exist * * * * * echo hello_world

它一直在工作,直到我使用命令crontab -r删除 cron 作业,现在我的 python 输出说 cron 作业已经存在。

不知道我的错误是什么 - 请帮助..(或者,如果有更好的方法可以在本地用户中找到 cron 作业,请提供帮助(。

问题是您在检查是否存在之前已经初始化了新的 Cron 作业。您假设Cron.find_command()只是标识已启用的 cron 作业。但它也可以识别已创建但尚未启用的 cronjob。

因此,您必须在创建新作业之前检查 cronjob 是否存在。然后,如果它不存在,您可以创建一个新的 cron 作业并启用它。您可以尝试以下代码:

import os
from crontab import CronTab
cron = CronTab("ansible")
basic_command = "* * * * * echo hello_world"
basic_iter = cron.find_command("hello_world")
exsist=False
for item in basic_iter:
if str(item) == basic_command:
print("crontab job already exist", item)
exsist=True
break
if not exsist:
job = cron.new(command='echo hello_world')
job.minute.every(1)
job.enable()
cron.write()
print("cronjob does not exist and added successfully.. please see "crontab -l" ")

另一种解决方案可能是将项目添加到列表中,因为 find 命令的输出是一个生成器对象,但通过将项目放入列表中可以更轻松地处理。这就是我为解决您遇到的问题所做的 下面基于已经初始化的其他所有内容

List_A=[]
basic_iter = cron.find_command("hello world")
for item in basic_iter:
List_A.append(item)
#From there you can do more but here are 2 examples
if len(List_A) == 0:
#create cronjob
else:
#don't create cron job
#or you could do a for loop comparing if you want to iterate
for i in List_A:
if i =="hello world": don't create cron job
else: create cron job

希望这有帮助抱歉格式化这是我第一次

最新更新