Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

Monitor owner and permissions changes

A user on the Fedora forum asked for assistance monitoring owner and permissions changes to files. I whipped up a general solution in shell. It uses a compressed database to store the last run, and will show the changes of the requested attributes of each file. Here's some of the business logic.

   # not empty
   test -n "${CO_DEBUG}" && echo "Comparing ${CO_INPUT} to database ${CO_OUTPUT}"

   # learn current status
   scan_dir "${CO_INPUT}" > "${CO_TMPFILE}"

   # compare to database
   zcat "${CO_OUTPUT}" | diff -W300 --suppress-common-lines -y "-" "${CO_TMPFILE}"

   # replace database
   cat "${CO_TMPFILE}" | gzip > "${CO_OUTPUT}"

And the scan function is pretty simple. Just change what stat outputs if you want to monitor different file characteristics.

scan_dir() {
   # call: scan_dir "${CO_INPUT}"
   # output: listing of hash, owner+perm hash for each file
   local td="${1}"

   find "${td}" -exec stat -L -c '%u,%U,%g,%G,%a,%n' {} + 2>/dev/null | sort -t ',' -k6
}

The script stores its compressed databases in /var/cache/check-owners/, and it will make files named based on the base directory it scans, so /home would be db file /var/cache/check-owners/co.home.db.gz. You could write a cron entry to call this once a day on a particular directory and email the output to you. A poor man's AIDE, if you will.

Comments