Why is crond failing to run a non-root crontab on alpine linux?

Why is crond failing to run a non-root crontab on alpine linux? Техника

Question

I created this test bash script

#! /bin/bash
echo "hello"
mkdir "/karan/washere"

cron job i created, i want to run this cron job to run every min and want the log

#testing if cron job workes or not
1 * * * * /user/local/bin/bash /root/test.sh &> /root/crontest.log

I also have given the permission for the script, using

sudo chmod u+x test.sh

I tried to log the syslog using

sudo grep CRON /var/log/syslog

but didn’t show there also,

let me know if you need any more info or other context,


Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer


These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

card icon

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

card icon

Hollie’s Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We’d like to help.

card icon

Become a contributor

You get paid; we donate to tech nonprofits.

Get started for free

Enter your email to get $200 in credit for your first 60 days with DigitalOcean.

New accounts only. By submitting your email you agree to our Privacy Policy.

Unless you’ve skipped some characters when writting the syslog output in your question, it looks like you’ve made a typo in your CRON command by forgetting the / in front of the command that should looks like :

/home/wayne/scripts/mysql_backup.sh

Cron Jobs For Beginners | Linux Task Scheduling

12 : 47

Crontab command error "You (user) are not allowed to access to (cron) because of pam configuration"

05 : 26

Ubuntu: crontab not running as root

02 : 08

Ubuntu: crontab not running as root

Root crontab not running

02 : 35

Why won't my cron jobs work? Scheduling jobs in Linux for subscriber

11 : 19

Why won’t my cron jobs work? Scheduling jobs in Linux for subscriber

Computer Programming University

Comments

  • Mysql backup scripts not running as root crontab — help

    I’m trying to run a crontab as root but the script is not running successfully. I can see in syslog that the script is executing but it does not finish.

    MyUSER="root" # USERNAME
    MyPASS="devan13" # PASSWORD
    MyHOST="localhost" # Hostname
    # Linux bin paths, change this if it can not be autodetected via which command
    MYSQL="$(which mysql)"
    MYSQLDUMP="$(which mysqldump)"
    CHOWN="$(which chown)"
    CHMOD="$(which chmod)"
    GZIP="$(which gzip)"
    # Backup Dest directory, change this if you have someother location
    DEST="/home/wayne/backup"
    # Main directory where backup will be stored
    MBD="$DEST/mysql"
    # Get hostname
    HOST="$(hostname)"
    # Get data in dd-mm-yyyy format
    NOW="$(date +"%d-%m-%Y")"
    # File to store current backup file
    FILE=""
    # Store list of databases
    DBS=""
    # DO NOT BACKUP these databases
    IGGY="thisdatabaseschema thatdatabase herdata mydata"
    [ ! -d $MBD ] && mkdir -p $MBD || :
    # Only root can access it!
    $CHOWN 0.0 -R $DEST
    $CHMOD 0600 $DEST
    # Get all database list first
    DBS="$($MYSQL -u $MyUSER -h $MyHOST -p$MyPASS -Bse 'show databases')"
    for db in $DBS
    do
    skipdb=-1
    if [ "$IGGY" != "" ];
    then
    for i in $IGGY
    do
    [ "$db" == "$i" ] && skipdb=1 || :
    done
    fi
    if [ "$skipdb" == "-1" ] ; then
    FILE="$MBD/$db.$HOST.$NOW.gz"
    # do all inone job in pipe,
    # connect to mysql using mysqldump for select mysql database
    # and pipe it out to gz file in backup dir :)
    $MYSQLDUMP --quick -u $MyUSER -h $MyHOST -p$MyPASS $db | $GZIP -9 > $FILE
    fi
    done

    • I hope your mysql password is not actually ‘devan13’. If so, you’ll probably want to change it now that you’ve posted it in a public forum.

    • I suggest adding a shebang (#!/bin/bash) as the first line of your script.

I am having a nasty time running a non-root crontab file on Alpine Linux.

Дополнительно:  Почему не работают некоторые кнопки на клавиатуре ноутбука и компьютера

Here is the setup.

My crontab looks like this:

PATH=/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/opt/aws/bin:/home/ec2-user/bin
SHELL=/bin/bash
* * * * * /opt/monitor/monitor.sh >> /var/log/monitor.log 2>&1
0 3 * * * /opt/monitor/monitor-log-clean.sh >> /var/log/monitor.log 2>&1
FROM alpine:3.5
# DEPENDENCY TO ALLOW USERS TO RUN crontab -e
RUN apk add --update busybox-suid
# I LIKE BASH
RUN apk --no-cache add bash bash-doc
RUN apk --no-cache add util-linux pciutils usbutils coreutils binutils findutils grep
#... lots of custom stuff ...
# CREATE USER
RUN adduser -S robuser && \ mkdir -p /home/robuser
# ADD ENTRY POINT
ADD src/entrypoint.sh /home/robuser/entrypoint.sh
# GIVE MY USER ACCESS
RUN mkdir /etc/cron.d
RUN echo "robuser" > /etc/cron.allow
RUN echo "" >> /etc/cron.allow
RUN chmod -R 644 /etc/cron.d
# ADD MY CRONTAB
RUN mkdir -p /var/spool/cron/crontabs
ADD ./src/crontab.conf /tmp/cloudwatch/crontab.conf
RUN crontab -u robuser /tmp/cloudwatch/crontab.conf
# DEBUG... GIVE MY USER ACCESS TO EVERYTHING
RUN chown -R robuser /etc/cron.d
RUN chmod -R 755 /etc/cron.d
RUN chown -R robuser /var/spool/cron
RUN chmod -R 744 /var/spool/cron
RUN chown robuser /var/spool/cron/crontabs
RUN chmod 744 /var/spool/cron/crontabs
RUN chown -R robuser /etc/crontabs
RUN chmod -R 744 /etc/crontabs
RUN chown robuser /etc/crontabs/robuser
RUN chmod -R 744 /etc/crontabs/robuser
RUN chmod 600 /var/spool/cron/crontabs/robuser
# ADD MY MONITORING PROGRAM
RUN mkdir -p /opt/monitor
ADD src/monitor /opt/monitor
RUN mkdir -p /opt/monitor/.tmp && \ chown -R robuser /opt/monitor && \ chmod -R 700 /opt/monitor
RUN touch /var/log/entrypoint.log && \ touch /var/log/monitor.log && \ touch /var/log/cron.log && \ touch /var/log/awslogs.log && \ chown -R robuser /var/log
USER robuser
ENTRYPOINT /home/robuser/entrypoint.sh

meanwhile, my entrypoint.sh has this somewhere in it. I start the cron daemon as a background service and log to cron.log verbosely. I’ve also tried specifying -d 0 to get even more debug, but the didn’t really add anything to the output.

#!/bin/bash
crond -b -l 0 -L /var/log/cron.log
#... lots of other startup stuff ...

If I check the cron.log, its pretty empty:

crond: crond (busybox 1.25.1) started, log level 0
crond: wakeup dt=45
crond: wakeup dt=60
crond: wakeup dt=60

Meanwhile, /var/log/monitor.log is completely empty (see crontab at the beginning of the post).

So crond is not printing any errors.

I’ve tried everything i can think of to debug this. There’s no error message. It simply runs and never prints. A good suggestion was to simply my crontab.. but this also did not work:

PATH=/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/opt/aws/bin:/home/ec2-user/bin
SHELL=/bin/bash
* * * * * touch /tmp/test.txt

I’ve tried searching for other alpine containers who use non-root cron, but most people don’t go through the trouble of getting their alpine containers to run non-root.

Does anyone have any further suggestions to help debug this?

Why is crond failing to run a non-root crontab on alpine linux?

Тема: Запуск программы в crontab с правами root  (Прочитано 23057 раз)

0 Пользователей и 2 Гостей просматривают эту тему.

joni2009ok

Такая проблема запуск бэкапа в кронтаб
В данный момент такая команда

MAILTO=epashkov@pngtools.ru
0 00 * * * /usr/local/fsbackup/create_backup.sh

Но она от туда не запускается.
Пробую с консоли, просит права админа, пишу в командной строке sudo /usr/local/fsbackup/create_backup.sh
Ввожу  пароль все работает!

Так вот как мне в кронтаб запустить эту команду с правами админа?
Строки
 0 00 * * * sudo /usr/local/fsbackup/create_backup.sh
Видимо мало, пробовал не получается.

ubuntu 8.10 server
fsbackup 1.2


Оффлайн
Belyaev Nikolay

ey просто ради проверки
#!/bin/sh
стоит в самом начале скрипта

«Сначала они вас игнорируют, потом смеются над вами, потом борются с вами, а потом вы побеждаете»
Махатма Ганди


Оффлайн
vasilisc

из крона проги запускаются от прав рута если указано в поле юзверя слово root
проверьте лучше ваш кронтаб и особенно поле юзверь (6 поле)

вот например мой кронтаб


joni2009ok

из крона проги запускаются от прав рута если указано в поле юзверя слово root
проверьте лучше ваш кронтаб и особенно поле юзверь (6 поле)

вот например мой кронтаб

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

это мой кронтаб

*******************************************
  *                                         *
  *        W E L C O M E  to  R O O T       *
  *                                         *
  *   Version  5.18/00b     10 March 2008   *
  *                                         *
  *  You are welcome to visit our Web site  *
  *          http://root.cern.ch            *
  *                                         *
  *******************************************

‘ expected at or after line 9.
Error: Unexpected end of file (G__fgetname():2) /usr/local/fsbackup/create_backup.sh:39:
Error: Missing one of ‘

‘ expected at or after line 9.
Error: Unexpected end of file (G__fgetname():2) /usr/local/fsbackup/create_backup.sh:39:
Error: Missing one of ‘

‘ expected at or after line 9.
Error: Unexpected end of file (G__fgetname():2) /usr/local/fsbackup/create_backup.sh:39:
Error: Missing one of ‘

‘ expected at or after line 9.
Error: Unexpected end of file (G__fgetname():2) /usr/local/fsbackup/create_backup.sh:39:
Error: Missing one of ‘

‘ expected at or after line 9.
Error: Unexpected end of file (G__fgetname():2) /usr/local/fsbackup/create_backup.sh:39:
Error: Unexpected end of file (G__fgetc()) /usr/local/fsbackup/create_backup.sh:39:


joni2009ok

ey просто ради проверки
#!/bin/sh
стоит в самом начале скрипта

Не понял. Вначале у меня ничего не стоит. Смотрите выше.
Что это за команда?


Оффлайн
Belyaev Nikolay

внутри скрипта (create_backup.sh в вашем слачае) первая строка показывает какую оболочку надо запускать sh, bash или ещё что
один раз писал скрипт он классно выполнялся с консоли, но из под крона нет. потому как просто забыл написать эту строку.

«Сначала они вас игнорируют, потом смеются над вами, потом борются с вами, а потом вы побеждаете»
Махатма Ганди


Оффлайн
Lion-Simba

Тварищи, кронтабы бывают разные!

Есть общесистемный (рутовый) кронтаб, который настраивается путем правки файла /etc/crontab

И есть пользовательские кронтабы, которые настраиваются пользователями при помощи команды crontab -e

Оказываю индивидуальную платную техподдержку широкого профиля. Обращаться в ЛС или Jabber.


joni2009ok

Тварищи, кронтабы бывают разные!

Есть общесистемный (рутовый) кронтаб, который настраивается путем правки файла /etc/crontab

И есть пользовательские кронтабы, которые настраиваются пользователями при помощи команды crontab -e

Правлю в crontab -e     :coolsmiley:


Оффлайн
zloy tapok

У меня от рута все чудесно пашет, когда сделать sudo crontab -e


Оффлайн
Belyaev Nikolay

Правлю в crontab -e

надо в sudo crontab -e

«Сначала они вас игнорируют, потом смеются над вами, потом борются с вами, а потом вы побеждаете»
Махатма Ганди


joni2009ok

Уфффффффф
Чет туговато у меня с этим crontab
Что делаю конкретно

В консоли crontab -e

# m h  dom mon dow   command
MAILTO=epashkov@pngtools.ru
50 15 * * * root /usr/local/fsbackup/create_backup.sh &>/tmp/cron.log

Не пашет
—————————————————————————-
В консоли sudo crontab -e

# m h  dom mon dow   command
MAILTO=epashkov@pngtools.ru
50 15 * * * root /usr/local/fsbackup/create_backup.sh &>/tmp/cron.log

Не пашет
—————————————————————————-
Открываю общесистемный (рутовый) кронтаб /etc/crontab

HELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

Не пашет
—————————————————————————-
Может я что то со временем не так пишу?
Лог пустой


Оффлайн
wl

А вот что после выполнения с root

*******************************************
  *                                         *
  *        W E L C O M E  to  R O O T       *
  *                                         *
  *   Version  5.18/00b     10 March 2008   *
  *                                         *
  *  You are welcome to visit our Web site  *
  *          http://root.cern.ch            *
  *                                         *
  *******************************************

Следует различать пользователя root, имеющегося в юниксах, и программный продукт ROOT, написанный в ЦЕРНе, что в Швейцарии под Женевой, для обработки результатов ядерно-физических экспериментов (он появился несколько раньше БАК).

« Последнее редактирование: 13 Марта 2009, 16:10:49 от wl »

На свете феньки есть такие, брат Горацио, которых лохи просто не секут. (Шекспир, «Гамлет», вольный перевод)


Оффлайн
SkeL2007

В консоли sudo crontab -e
# m h  dom mon dow   command
MAILTO=epashkov@pngtools.ru
50 15 * * * root /usr/local/fsbackup/create_backup.sh &>/tmp/cron.log
Не пашет

Тебе же сказали  в пользовательском кронтабе поля «юзер» нет. Убери «root»

« Последнее редактирование: 13 Марта 2009, 16:27:43 от SkeL2007 »


joni2009ok

В консоли sudo crontab -e
# m h  dom mon dow   command
MAILTO=epashkov@pngtools.ru
50 15 * * * root /usr/local/fsbackup/create_backup.sh &>/tmp/cron.log
Не пашет

Тебе же сказали  в аользовательском кронтабе поля «юзер» нет. Убери «root»

Да и без рут не пашет


Оффлайн
zloy tapok


Solution 1

I have three solution suggestions for you.

  1. Invoke the crontab with crontab -e -u root

  2. Make sure that you have an empty line at the end of the cronjob file, meaning that every line ends with a newline.

  3. You might need to redirect the output to devnull: shutdown -r now > /dev/null

Here are two helpful webpages for cronjobs:

You can also handle the cronjobs neatly with webmin.

Other than that, you have at least two more ways for restarting your computer at midnight.

One is to run the shutdown command as a script automatically at login but with specific time as a parameter instead of «now»:

shutdown -r 00:00

However, this will yield a broadcast message of upcoming shutdown at every login (might not be a bad thing at all). Well you can also make this be run at boot time by adding the script in init.d, still yielding the message, though.

Another is to use atcommand:

Enter command shutdown -r now and save it with ctrl+d or do a script for the command and do:

at -f restart_script.sh 0am

Hope these help you to get the result you wanted.

Solution 2

System Cron jobs are listed in /etc/crontab file. Therefore editing this file directly will help you out to run the reboot command as root.

$ sudo vi /etc/crontab
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed 23 20 * * * root shutdown -r now

make sure you check the Cron log file after editing the crontab as it will let you know if the cron was installed successfully.

I have tested it and it worked for me. Restarted my system at 8:23 PM

Crontab command error "You (user) are not allowed to access to (cron) because of pam configuration"

05 : 26

Root Crontab Not Running Python Script

01 : 32

Root Crontab Not Running Python Script

Root crontab not running

02 : 35

root crontab not executing (2 Solutions!!)

02 : 35

root crontab not executing (2 Solutions!!)

Why won't my cron jobs work? Scheduling jobs in Linux for subscriber

11 : 19

Why won’t my cron jobs work? Scheduling jobs in Linux for subscriber

Computer Programming University

Comments

  • I’m building a CNN with Keras that predicts the coordinates of 13 keypoints in every image. The images I have vary in input dimension so my input layer shape is (None, None, 3). I am using Inception Modules so I am using the Functional API. Now, while coding the last layers for my model, I encountered a problem. As far as I know, my output layer wil be a Dense(26) layer, since I will encode the x and y coordinates as a vector. I have trouble connecting the output layer with the preceeding Convolutional layers (because of tensor dimensions)

    x = Input(None, None, 3)
    stage_1 = Conv2D(26, (1, 1))(x)
    stage_1 = Dropout(0.3)(stage_1)
    stage_2 = Conv2D(512, (1, 1))(x)
    stage_2 = Dropout(0.3)(stage_2)
    stage_2 = Activation('relu')(stage_2)
    x = concatenate([stage_1, stage_2])
    x = Lambda(lambda i: K.batch_flatten(i))(x)
    outputs = Dense(26)(x)

    I tried including a Flatten Layer (but it is not compatible with arbitrary input shapes) and I’ve tried using K.batch_flatten() in a Lambda layer (which also did not work.) My question is: Is there a different way to get an output layer in a similar shape ((13,2) would also be fine, I just only found models online where the output layer is a Dense layer)? I also tried GlobalAveragePooling2d(), but this greatly decreased the accuracy of the model. Also, using a function to find the output shape did not work, see below

    stage_1 = Conv2D(26, (1, 1))(x)
    stage_1 = Dropout(0.3)(stage_1)
    stage_2 = Conv2D(512, (1, 1))(x)
    stage_2 = Dropout(0.3)(stage_2)
    stage_2 = Activation('relu')(stage_2)
    x = concatenate([stage_1, stage_2])
    def output_shape_batch(tensor_shape): print(tensor_shape) return (batch_size, tensor_shape[1] * tensor_shape[2] * tensor_shape[3])
    x = Lambda(lambda i: K.batch_flatten(i), output_shape=output_shape_batch)(x)
    outputs = Dense(26)(x)

    I expect the model to compile, but get TypeErrors
    The error is:
    TypeError: unsupported operand type(s) for *: ‘NoneType’ and ‘NoneType’

    • Why is this tagged debian? If this is about Debian and not Ubuntu, please ask on Unix & Linux.

    • Because debian is at the core of Ubuntu I believe.

  • Not true! Cron does not use 12 hour time format and the format is always mm hh DD MM WD.

  • The solution was to output to dev null. I wonder why?

  • Please read the whole post next time.

Оцените статью
Master Hi-technology