Created
June 24, 2017 20:18
-
-
Save inesusvet/eec643d8b33415e15743aec097192997 to your computer and use it in GitHub Desktop.
Watch dog which knows only one trick
This file contains 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
""" | |
Watchdog which can do one trick only - to sniff for a pattern in a log file and | |
"bark" by running some command. The program won't stop after "barking". | |
Usage: | |
python watch_bro.py <filename> <pattern> <command> | |
filename: A file to watch for changes | |
pattern: A string to look for in the file | |
command: What to execute when the pattern occurs | |
Example: | |
python watch_bro.py nginx.log 111.222.33.44 reboot | |
""" | |
import re | |
import subprocess | |
import sys | |
import time | |
def iter_changes(filename): | |
with open(filename) as input: | |
input.seek(0, 2) | |
while True: | |
line = input.readline() | |
if line == '': | |
time.sleep(1) | |
else: | |
yield line | |
def run(cmd): | |
try: | |
return subprocess.check_call(cmd.split(' '), shell=True) | |
except subprocess.CalledProcessError: | |
print('Command %r return code is not zero' % cmd) | |
exit(1) | |
def main(filename, pattern, cmd): | |
re_pattern = re.compile(pattern, re.U) | |
for line in iter_changes(filename): | |
search = re_pattern.search(line) | |
if search: | |
run(cmd) | |
if __name__ == '__main__': | |
if len(sys.argv) != 4: | |
print(__doc__) | |
exit(1) | |
file_to_watch, pattern_to_look, cmd_to_run = sys.argv[1:] | |
exit(main( | |
file_to_watch, | |
pattern_to_look, | |
cmd_to_run, | |
)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment