Skip to content

Instantly share code, notes, and snippets.

@iacchus
Last active December 5, 2017 16:16
Show Gist options
  • Save iacchus/8560932c373a53029999ad6c8d6f637d to your computer and use it in GitHub Desktop.
Save iacchus/8560932c373a53029999ad6c8d6f637d to your computer and use it in GitHub Desktop.
Simple logwatcher in python 3 like swatch

This is a simple log watcher written in python 3, works similar to swatch (perl).

DEPRECATION WARNING: maybe you would like more this one https://gist.github.com/iacchus/acbd0ca89c1bd4a1deb7a472dfee931b

logwatcher.python3

#!/usr/bin/env python3

# follow.py
#
# Follow a file like tail -f.

import sys
import os
import time

def follow(thefile):
    thefile.seek(0,2)
    while True:
        line = thefile.readline()
        if not line:
            time.sleep(0.5)
            continue
        yield line

if __name__ == '__main__':
    logfilename = sys.argv[1]
    pattern_string = sys.argv[2]
    command_to_execute = sys.argv[3]

    print("Log filename is: {}".format(logfilename))

    logfile = open(logfilename, "r")
    loglines = follow(logfile)

    for line in loglines:
        if startup_string in line:
            os.system(command_to_execute)

Usage

1. Make the above script executable:

chmod +x logwatcher.python3

2. Add a cronjob to start it after reboot

@reboot /home/YOURUSERNAME/logwatcher.python3 "/var/log/auth.log" "session opened for user" "/sbin/myscript.sh"

Arguments for this script

The first argument of this script is the log file to watch, and the second argument is the string for which to look in it. The third argument is the script to execute when the line is found in file.

It is best if you use something more reliable to start/restart the script in case it crashes than cron.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment