Pete Freitag Pete Freitag

Bash Script to log file modifications with osquery

Published on April 09, 2021
By Pete Freitag

Here's a bash script that uses osquery to log which files in a specific folder have been modified over a 15 minute period. My use case here wasn't file integrity monitoring, for that you would want to use file events.

Here's the script:


WORKSPACE_DIR=`echo ~/workspace`
LOG_DIR=`echo ~/Documents/Logs/osquery_file_logs/`
AGO_TIMESTAMP=`date -v-15M "+%s"`
LOG_FOLDER_NAME=`date "+%Y-%m"`
LOG_FILE_NAME=`date "+%Y-%m-%d"`


touch $LOG_FILE

/usr/local/bin/osqueryi --csv --header=false "SELECT datetime(mtime,'unixepoch') AS file_last_modified_time, path FROM file WHERE path LIKE '$WORKSPACE_DIR/%%' AND type != 'directory' AND mtime > $AGO_TIMESTAMP ORDER BY mtime ASC;" >> $LOG_FILE

I tested this bash script on a Mac, but I think it would work just the same on linux. You'll need to install osquery first. If you set this up in a cron job running every 15 minutes, you'll have a nice log of what files where changed when.

It has occurred to me that using osquery here is probably a bit overkill for this task, I think you could create a more rudimentary version of this script like this:

find $WORKSPACE_DIR -type f -newer $LOG_DIR/timestamp >> $LOG_FILE
touch $LOG_DIR/timestamp 

Using the -newer flag of the find command it will return all files newer than our $LOG_DIR/timestamp, and because we touch that file after the script runs, the next time it runs it will show all files changed since it was last run.

That doesn't include the last modified dates in the log file, but it is possible to do with a little more work.

mac bash osquery

Bash Script to log file modifications with osquery was first published on April 09, 2021.

If you like reading about mac, bash, or osquery then you might also like:

Discuss / Follow me on Twitter ↯