如何在python脚本中使用cron执行我的django自定义命令

时间:2014-10-15 04:09:57

标签: django cron

我创建了一个Django自定义命令。我想在特定的时间(例如每5分钟)运行此命令。我如何从我的脚本或终端进行此操作。

我的django自定义命令在periodic_tasks.py中:

`class Command(BaseCommand):     help ='显示数据....'

def handle(self, *args, **options):
        hostip = '192.168.1.1'
        cmd = 'sudo nmap -sV -T4 -O -F --version-light -oX - '+hostip
        scandate = timezone.now()
        #scandate = datetime.datetime.now()
        self.addToLog('Detailed Scan',hostip,scandate,'Started')
        child = pexpect.spawn(cmd, timeout = 60)
        index = child.expect (['password:',pexpect.EOF, pexpect.TIMEOUT])
        child.sendline('abcdef')
        scandate = timezone.now()
        self.addToLog('Detailed Scan',hostip,scandate,'Finished')
        print 'before xml.....'
        with open('portscan.xml', 'w') as fObj:
            fObj.write(child.before)
            print 'in xml.....'
        print 'after xml.....'
        portscandata = self.parsexml()
        self.addToDB(portscandata,hostip)`

在我的脚本中,我试图这样做:

test = subprocess.Popen(["*/5","*","*","*", "*", "/usr/local/bin/python2.6","periodic_tasks"], stdout=subprocess.PIPE) output = test.communicate()[0]

我正试图从终端运行这个:

*/5 * * * * root /usr/local/bin/python2.6 /home/sat034/WorkSpace/SAFEACCESS/NetworkInventory/manage.py periodic_tasks

这是说: bash:* / 5:没有这样的文件或目录

如果我在某个地方遗失,请建议我。在此先感谢

1 个答案:

答案 0 :(得分:0)

你的字符串

*/5 * * * * root /usr/local/bin/python2.6 /home/sat034/WorkSpace/SAFEACCESS/SynfosysNetworkInventory/manage.py periodic_tasks

看起来像cron配置字符串。您可以使用crontab -e将其添加到cron(编辑器将启动,因此您将添加此行)

此行的含义是“每隔5分钟运行一次命令”

在添加到cron之前我建议测试此命令运行它而不使用* / 5 * * * *