21 April 2023

A Simple Script for Listing Every Cron

Topics: Linux
Remarkably there is no well known Linux utility for listing out every cron job on a system, a task which Systems Administrators frequently need to do.

This script without arguments will give you all your local cron jobs, and with the arguments you would use to the ssh command for connecting as a remote user will run on the remote host, and prompt for the user’s sudo password. Since systemctl list-timers spews screenfuls of information I used jq to filter the output.

Listing of everycron:

#!/bin/bash

# list all the crons and systemd timers
# for the systemd timers output is piped through jq
# to produce a more readable list if you don't
# expect jq on your systems use
# systemctl list-timers by itself.

function EC () {
   echo -e "\n*** $1 ***\n"
}

if [ $# -eq 0 ]; then
  if [ "$EUID" -ne 0 ]
    then echo "Must run as root for local cron listing"
    exit
  fi
  EC '/etc/cron*'
  ls -b /etc/cron*
  EC 'User Crons'
  cd /var/spool/cron/crontabs ; grep -rvH '#' *
  EC "systemd timers"
  systemctl list-timers --output=json --no-pager | jq '.[].unit'
else
  EC '/etc/cron*'
  ssh "$@" -t 'ls -b /etc/cron*'
  EC 'User Crons'
  ssh "$@" -t "sudo sh -c \"grep -rvH '#' /var/spool/cron/*\""
  EC "systemd timers"
  ssh "$@" -t "sudo sh -c \"systemctl list-timers --output=json --no-pager | jq '.[].unit'\""
fi

echo -e "\n*****\n"