Created
December 5, 2017 16:14
-
-
Save iacchus/acbd0ca89c1bd4a1deb7a472dfee931b to your computer and use it in GitHub Desktop.
Simple logwatcher in python3. Watchs a log file for a line with a stiing, then runs an executable with the line as arguments.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# usage | |
# | |
# 1. Make the above script executable: | |
# chmod +x logwatcher.py | |
# | |
# 2. Add a cronjob to start it after reboot like: | |
# @reboot /home/YOURUSERNAME/logwatcher.py "/var/log/auth.log" "session opened for user" "/sbin/myscript.sh" | |
# | |
# arguments are: | |
# ./logwatcher.py <log_file_to_watch> <string_to_look_for> <script_to_execute_then> | |
import sys | |
import os | |
import time | |
from subprocess import Popen | |
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 pattern_string in line: | |
Popen(args=line.split(' '), executable=command_to_execute) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment