在crontab中使用shell脚本中的python3



我尝试运行一个带有python3脚本的crontab的shell脚本。crontab适用于用户组。现在,它运行脚本,但不运行其中的python3脚本。我尝试调试它,但我不知道会发生什么。这可能是一个许可问题或路径问题,但我不知道。这是crontab行

*/5 * * * * /home/group_name/path/to/script/run.sh

我说的是执行cron的工作,或者至少是我想的,因为我运行sudo grep CRON /var/log/syslog时,我会得到

之类的行
 Feb 16 20:35:01 ip-**-**-*-*** CRON[4947]: (group_name) CMD (/home/group_name/path/to/script/run.sh)

就在下面我还获得了一条可能与问题有关的行

Feb 16 20:35:01 ip-**-**-*-*** CRON[4946]: (CRON) info (No MTA installed, discarding output)

最后run.sh看起来像

#!/bin/bash
# get path to script and path to script directory
SCRIPT=$(readlink -f "$0")
SCRIPTPATH=$(dirname "$SCRIPT")
echo "set directory"
cd "$SCRIPTPATH"
echo "run first script"
/usr/bin/python3 ./first_script.py > ./log1.txt

但是,当Cron作业执行什么都没有发生时,当我手动运行它时,CAHNGES到数据库时会按预期发生。该小组具有与我相同的权利。我可以执行shell文件,组和python文件不能由我执行,所以我不知道为什么组需要这个。

ps:我想在外壳中执行python脚本,因为我们有很多脚本有很多参数,因此crontab会被人口过多,并且某些脚本必须以一定顺序执行。p>编辑:#! /bin.bash之后立即添加exec >> /tmp/output 2>&1,每当我手动运行它时,将Echoes写入/tmp/output,但在我在CRON中运行时不会,甚至在运行任何Python脚本之前都没有。

直接从cron运行python脚本之一,但是即使我将粘贴与在cron中工作的一行完全相同,也没有发生任何事情。

这个问题有很多组成部分。我忽略了MTA错误,因为当您的CRON工作完成时,这只是电子邮件通知。我还假设您的权限设置正确,并且在手动运行时,您的脚本运行正常。

最大的问题是,cron命令与从终端" shell"运行命令并不相同。您必须指定使用bash运行脚本。从:

更改您的Cron工作
*/5 * * * * /home/group_name/path/to/script/run.sh 

to:

*/5 * * * * bash /home/group_name/path/to/script/run.sh

这个问题有更多信息和其他解决问题的选项。

更改此行:

*/5 * * * * /home/group_name/path/to/script/run.sh

to:

*/5 * * * * cd /home/group_name/path/to/script && /home/group_name/path/to/script/run.sh

关于/var/log/syslog,当您查看/var/log/syslog时,查看时间戳以找出是否正在运行cron作业。

关于无法写入log.txt的cron作业,这可能与权限有关。尝试更改此行:

/usr/bin/python3 ./first_script.py > ./log1.txt

to:

/usr/bin/python3 /full/path/to/first_script.py > /tmp/log1.txt

看看是否有区别。克朗应该能够写入/tmp。

1(消息"未安装的MTA"并不意味着任何错误,仅表示没有邮件服务器CRON无法报告任何详细信息。

修改Cron作业以将其输出记录到Syslog中:

*/5 * * * * /home/group_name/path/to/script/run.sh 2>&1 | /usr/bin/logger -t run.sh

然后通过sudo tail -f /var/log/syslog检查结果(或Redhat和Suse上的sudo tail -f /var/log/messages(

另外,安装后缀并将其配置为"仅本地"交付:

sudo apt-get install postfix

然后将邮件作为group_name用户检查。

2(run.sh中的重定向> ./log1.txt应在每个执行时覆盖日志文件。如果Python脚本失败而例外,则log1.txt将保持截断为零长度。在这种情况下,修改run.sh的最后一行:

/usr/bin/python3 ./first_script.py 2>&1 > ./log1.txt

并检查结果。

如果log1.txt既不被截断,也没有包含新的输出,则根本没有启动Python脚本。请参阅步骤1(调试run.sh

bash脚本中的最后一行包含相对路径(./(我相信这是问题

当前对这个问题有很多猜测,这是因为您的系统无法向您发送失败电子邮件以确切解释问题是什么。不久前,我遇到了一个类似的问题,试图设置一个实际的邮件系统不知所措,所以写了一个简短的邮件转发 sendmail 替补替补: pygeon_mail

#!/usr/bin/python
from __future__ import with_statement
from email.mime.text import MIMEText
import email
import os
import pwd
import smtplib
import stat
import sys
import syslog
import traceback

CONFIG = '/etc/pygeon_mail.rc'
# example config file
#
# server=mail.example.com
# port=25
# domain=example.com
# host=this_pc_host_name
# root=me@example.com,you@example.com
# ethan=me@example.com
# debug=debug@example.com

def check_dangerously_writable(filename):
    "return the bits of group/other that are writable"
    mode = stat.S_IMODE(os.stat(filename)[0])       # get the mode bits
    if mode & (stat.S_IWGRP | stat.S_IWOTH):        # zero means not set
    syslog.syslog("%s must only be writable by root, aborting" % (filename, ))
    sys.exit(1)
def get_config(filename, config=None):
    "return settings from config file"
    check_dangerously_writable(filename)
    if config is None:
    config = {}
    with open(filename) as settings:
    for line in settings:
        line = line.strip()
        if line and line[:1] != '#':
        key, value = line.split('=')
        key, value = key.strip(), value.strip()
        config[key] = value
    return config
def mail(server, port, sender, receiver, subject, message):
    """sends email.message to server:port
    receiver is a list of addresses
    """
    msg = MIMEText(message.get_payload())
    for address in receiver:
    msg['To'] = address
    msg['From'] = sender
    msg['Subject'] = subject
    for header, value in message.items():
    if header in ('To','From', 'Subject'):
        continue
    msg[header] = value
    smtp = smtplib.SMTP(server, port)
    try:
    send_errs = smtp.sendmail(msg['From'], receiver, msg.as_string())
    except smtplib.SMTPRecipientsRefused as exc:
    send_errs = exc.recipients
    smtp.quit()
    if send_errs:
    errs = {}
    for user in send_errs:
        if '@' not in user:
        errs[user] = [send_errs[user]]
        continue
        server = 'mail.' + user.split('@')[1]
        smtp = smtplib.SMTP(server, 25)
        try:
        smtp.sendmail(msg['From'], [user], msg.as_string())
        except smtplib.SMTPRecipientsRefused as exc:
        if send_errs[user] != exc.recipients[user]:
            errs[user] = [send_errs[user], exc.recipients[user]]
        else:
            errs[user] = [send_errs[user]]
        smtp.quit()
    for user, errors in errs.items():
        for code, response in errors:
        syslog.syslog('%s --> %s: %s' % (user, code, response))
    return errs

if __name__ == '__main__':
    syslog.openlog('pygeon', syslog.LOG_PID)
    try:
    config = get_config(CONFIG)
    root = config.get('root')
    domain = config.get('domain', '')
    if domain:
        domain = '@' + domain
    sender = None
    receiver = []
    dot_equals_blank = False
    ignore_rest = False
    next_arg_is_subject = False
    redirect = False
    subject = ''
    for i, arg in enumerate(sys.argv[1:]):
        if next_arg_is_subject:
        subject = arg
        next_arg_is_subject = False
        sys.argv[i] = '"%s"' % (arg, )
        elif arg == '-s':
        next_arg_is_subject = True
        elif arg == '-i':
        dot_equals_blank = True
        elif arg[:2] == '-F':
        sender = arg[2:]
        elif arg[0] != '-':
        receiver.append(arg)
        else:
        pass
    command_line = ' '.join(sys.argv)
    if sender is None:
        sender = pwd.getpwuid(os.getuid()).pw_name
    sender = '%s@%s' % (sender, config['host'])
    if not receiver:
        receiver.append(pwd.getpwuid(os.getuid()).pw_name)
    limit = len(receiver)
    for i, target in enumerate(receiver):
        if i == limit:
        break
        if '@' not in target:
        receiver[i] = ''
        receiver.extend(config.get(target, target+domain).split(','))
    receiver = [r for r in receiver if r]
    server = config['server']
    port = int(config['port'])
    all_data = []
    text = []
    while True:
        data = sys.stdin.read()
        if not data:
        break
        all_data.append(data)
        if ignore_rest:
        continue
        for line in data.split('n'):
        if line == '.':
            if dot_equals_blank:
            line = ''
            else:
            ignore_rest = True
            break
        text.append(line)
    text = 'n'.join(text)
    message = email.message_from_string(text)
    errs = mail(server, port, sender, receiver, subject, message)
    except Exception:
    exc, err, tb = sys.exc_info()
    lines = traceback.format_list(traceback.extract_tb(tb))
    syslog.syslog('Traceback (most recent call last):')
    for line in lines:
        for ln in line.rstrip().split('n'):
        syslog.syslog(ln)
    syslog.syslog('%s: %s' % (exc.__name__, err))
    sys.exit(1)
    else:
    receiver = []
    debug_email = config.get('debug', None)
    if debug_email:
        receiver.append(debug_email)
    if errs and root not in receiver:
        receiver.append(root)
    if receiver:
        debug = [
            'command line:',
            '-------------',
            repr(command_line),
            '-' * 79,
            '',
            'sent email:',
            '-----------',
            text,
            '-' * 79,
            '',
            'raw data:',
            '---------',
            ''
            ]
        all_data = ''.join(all_data)
        while all_data:
        debug_text, all_data = repr(all_data[:79]), all_data[79:]
        debug.append(debug_text)
        debug.append('-' * 79)
        if errs:
        debug.extend([
            '',
            'errors:',
            '-------',
            ])
        for address, error in sorted(errs.items()):
            debug.append('%r: %r' % (address, error))
        debug.append('-' * 79)
        text = 'n'.join(debug)
        message = email.message_from_string(text)
        mail(server, port, 'debug@%s' % config['host'], receiver, subject+'  [pygeon_mail debugging info]', message)
    if errs:
        sys.exit(1)

它是为Python 2.5编写的,应使用2.6和2.7。

需要将其复制到/usr/sbin/sendmail,并具有0755的权限,并由root:

拥有

sudo cp pygeon_mail/usr/sbin/sendmail

sudo chown root:root/usr/sbin/sendmail

sudo chmod 0755/usr/sbin/sendmail

您需要创建一个/etc/pygeon_mail.rc配置文件(请参阅示例代码(。

然后您可以用以下内容进行测试:

$ echo一些有用的信息|sendmail自己-S"一些重要主题"

您希望您在普通电子邮件帐户中看到该电子邮件(您在/etc/pygeon_mail.rc文件中设置的电子邮件(。

之后,您应该能够获得实际错误,我们实际上可以帮助您

如果您记录了使用cron调用的脚本的输出,则可以发现错误很容易。尝试这样的事情:

*/10 * * * * sh /bin/execute/this/script.sh >> /var/log/script_output.log 2>&1

相关内容

  • 没有找到相关文章

最新更新