3

Is there a way to identify a script is being run as an at job instead of interactively from the shell by a user?

Some of our scripts have a guard to check if they're running in screen by checking $TERM. I'm trying to figure out if I can intelligently check how execution of the script was initiated so I can update that guard statement OR if I should add an option that should always be included when run from an at job.

cclark
  • 567
  • 2
  • 6
  • 14
  • You might want to look at http://stackoverflow.com/questions/3214935/can-a-bash-script-tell-if-its-being-run-via-cron – eltrai May 19 '15 at 11:03

3 Answers3

1

You could check the parent process name by using the ${PPID} environment variable and looking for that in ps.

Steve Wills
  • 685
  • 3
  • 6
0

Enable logging for the job-execution subsystems. More specifically, cron and at will log to syslog by default, so you simply need to ensure the logged events are persisted. You might want to add the following to your /etc/syslog.conf

## Log cron and at to /var/adm/scheduled.log
cron.*  /var/adm/scheduled.log 

After adding that, reboot the syslog daemon, to cause him to pick up the newly added configuration parameters. At that point, you have a record of the scheduled jobs that have been run, and can compare a job to the record of its execution. [1]

To check all users' schedules at a point-in-time, you may want to do the following, which would list their jobs in the report at /tmp/schedulereport

unlink /tmp/schedulereport ;
cat /etc/passwd |while read ROW ; do 
  LOGIN="$(echo ${ROW} |cut -d: -f1)" ; 
  SHELL="$(echo ${ROW} |cut -d: -f7)" ; 
  [[ "${SHELL}" == '/sbin/nologin' && "${SHELL}" == '/bin/false' ]] \
    && ATJOBS='Skipping AT queue for non-interactive user' \
    || ATJOBS="$(su - ${LOGIN} -c 'atq' 2>/dev/null)" ; 
  [[ "${SHELL}" == '/sbin/nologin' && "${SHELL}" == '/bin/false' ]] \
    && CRONJOBS='Skipping CRON queue for non-interactive user' \
    || CRONJOBS="$(su - ${LOGIN} -c 'crontab -l' 2>/dev/null)"  ; 
  echo -e "${LOGIN}:\nAT:\n${ATJOBS}\n\nCRON:\n${CRONJOBS}\n\n=====\n >>/tmp/schedulereport " ; 
  ATJOBS='' ;
  CRONJOBS='' ;
done

Of course, if you are wanting to prevent users who are not authorized from scheduling jobs, you can add only the authorized users to "cron.allow" and "at.allow" and all users not listed will be unable to run the "crontab" or "at" or "batch" commands.


1: Note, the star means debug-level logging, which can get very verbose. If the logs fill with unactionable information, you may want to replace the "*" with "info"

DTK
  • 1,688
  • 10
  • 15
0

Another option is to use pstree

$ pstree -lp | grep crond
        |-crond(2059)-+-crond(4445)---sh(4452)
        |             `-crond(4446)---sh(4453)

In this case both PID 4452 and 4453 are scripts that were launched via crond.

Luis
  • 306
  • 1
  • 2
  • 10