How to monitor syslog and get alerted when there is a certain entry?
Here, a script, in Python:
Checks file for changes every 5 seconds, if changed, it checks for the string. If string is found:
- the line in which it was found along with the current time is printed
-
[optional] notifies using
notify-send
- [optional] plays the default alert sound
Usage:
python3 LogMonitor.py [log file] [string to watch]
Optional arguments, to be put after the above
-
beep
and/ornotify
-- this will cause the script to beep and/or notify (usingnotify-send
) in addition to printing the message
So, if I want to watch /var/log/auth.log
for SSH and make a beep sound and notify me, I will:
python3 LogMonitor.py /var/log/auth.log SSH beep notify
Raw download (Right Click → Save link as): GitHub Gist
#!/usr/bin/env python
import os
import sys
import subprocess
import collections
import time
import mmap
try:
LOG_FILE = os.path.abspath(sys.argv[1])
WATCH_FOR = sys.argv[2]
except:
sys.stderr.write(
'Usage: %s [log file] [string to watch for]' % sys.argv[0])
sys.exit(1)
def action():
if 'beep' in sys.argv:
subprocess.Popen(['paplay', '/usr/share/sounds/ubuntu/notifications/Mallet.ogg'])
if 'notify' in sys.argv:
subprocess.Popen(['notify-send', 'LogMonitor', 'Found!'])
print(time.strftime('%Y-%m-%d %I:%M:%S %p'), 'Found! \n', i)
# basic Python implementation of Unix tail
def tail(file, n):
with open(file, "r") as f:
f.seek (0, 2) # Seek @ EOF
fsize = f.tell() # Get Size
f.seek (max (fsize-1024, 0), 0) # Set pos @ last n chars
lines = f.readlines() # Read to end
lines = lines[-n:] # Get last 10 lines
return lines
print(
'Watching of ' + LOG_FILE + ' for ' + WATCH_FOR +
' started at ' + time.strftime('%Y-%m-%d %I:%M:%S %p'))
mtime_last = 0
while True:
mtime_cur = os.path.getmtime(LOG_FILE)
if mtime_cur != mtime_last:
for i in tail(LOG_FILE, 5):
if WATCH_FOR.lower() in i.lower():
action()
mtime_last = mtime_cur
time.sleep(5)
Related videos on Youtube
Admin
Updated on September 18, 2022Comments
-
Admin over 1 year
There is a certain error which is always the same and I am getting in syslog, however I am not really sure what the error is being caused by so I would like to get alerted immediately whenever it occurs. Preferably I would like something like a script to monitor syslog for any lines containing that certain message, and if it is detected for it to immediately alert me through
notify-send
and then to log it in a file. I am running Ubuntu GNOME 16.04 with GNOME 3.20. How can I achieve this through a script? Or is there some software that would allow me to do this?-
Admin almost 8 years@BharadwajRaju: Oh right, sorry, a lot was happening and I forgot to do that!
-
userx almost 5 yearsYou can check fail2ban source for this kind of implementation. It looks for specific strings in syslog and bans host.
-
-
Admin almost 8 years@ParanoidPanda Did the script help?