Commit af965b40 authored by Benjamin Graillot's avatar Benjamin Graillot Committed by root

[loggrep.py] Ajout de loggrep.py

parent cc833cb1
#!/usr/bin/python3
import argparse
import grp
import os
import re
import subprocess
import shlex
import sys
GREP_ARGS = ['basic_regexp', 'byte_offset', 'color', 'count', 'extended_regexp', 'fixed_strings', 'ignore_case', 'invert_match', 'line_number', 'only_matching', 'perl_regexp', 'quiet', 'word_regexp']
GREP_VALUE_ARGS = {'regexp': 'e', 'max_count': 'm', 'after_context': 'A', 'before_context': 'B', 'context': 'C'}
FIL_NETS = r"((185.230.7[89])|(10.5[124]))"
WIFI_NETS = r"(10.53)"
SWITCHES_NETS = r"(10.231.100)"
BORNES_NETS = r"(10.231.148)"
MAC_REGEX = r'([0-9a-fA-F]{2})[:-]?([0-9a-fA-F]{2})[:-]?([0-9a-fA-F]{2})[:-]?([0-9a-fA-F]{2})[:-]?([0-9a-fA-F]{2})[:-]?([0-9a-fA-F]{2})'
IPv4_REGEX = r"^([0-9]{1,3}\.){3}[0-9]{1,3}$"
IPv6_REGEX = r"^[0-9A-Fa-f]{0,4}:(([0-9A-Fa-f]{0,4}:){0,5}[0-9A-Fa-f]{0,4}|[0-9A-Fa-f]{0,4}(:[0-9A-Fa-f]{0,4}){0,5}):[0-9A-Fa-f]{0,4}$"
PRISE_REGEX = r"[ABCGHIJKMPabcghijkmp][0-9]{3}"
LOGFILES = {
'cablage': "/var/log/cablage/global.log",
'wifi': "/var/log/wifi/global.log",
'filaire': "/var/log/filaire/global.log"
}
if __name__ == '__main__':
group = grp.getgrgid(os.getegid())
if group.gr_name != 'cableur':
# Relancer le script dans le groupe cableur
os.execvp('/usr/bin/sudo', ['sudo', '-g', 'cableur', '/usr/bin/python3'] + sys.argv)
exit(0)
parser = argparse.ArgumentParser(description='Effectue une recherche dans les logs à des fins de diagnostic.', allow_abbrev=False)
parser.add_argument('-t', '--type', metavar='TYPE', type=str, default='file', help="Examiner les logs en temps réel ('live') ou ceux qui sont déjà consignés ('file')")
parser.add_argument('-s', '--source', metavar='SOURCE', type=str, default='cablage', help='Fichier de log à examiner')
grep = parser.add_argument_group(title='Options pour grep', description='Voir man 1 grep pour l\'aide.')
grep.add_argument('-E', '--extended-regexp', action='store_true', help='')
#grep.add_argument('-F', '--fixed-strings', action='store_true')
#grep.add_argument('-G', '--basic-regexp', action='store_true')
#grep.add_argument('-P', '--perl-regexp', action='store_true')
#grep.add_argument('-e', '--regexp', metavar='PATTERN', type=str, default=None)
grep.add_argument('-i', '--ignore-case', action='store_true')
grep.add_argument('-v', '--invert-match', action='store_true')
#grep.add_argument('-w', '--word-regexp', action='store_true')
grep.add_argument('-c', '--count', action='store_true')
grep.add_argument('--color', action='store_true', help='always si activé')
grep.add_argument('-m', '--max-count', metavar='NUM', type=int, default=None)
grep.add_argument('-o', '--only-matching', action='store_true')
#grep.add_argument('-q', '--quiet', '--silent', action='store_true')
#grep.add_argument('-b', '--byte-offset', action='store_true')
grep.add_argument('-n', '--line-number', action='store_true')
grep.add_argument('-A', '--after-context', metavar='NUM', type=int, default=None)
grep.add_argument('-B', '--before-context', metavar='NUM', type=int, default=None)
grep.add_argument('-C', '--context', metavar='NUM', type=int, default=None)
grep.add_argument('pattern', metavar='PATTERN', type=str, nargs='?', default=None)
search = parser.add_argument_group(title='logsearch', description='Macros, impliquent -E et -i, ignorées si PATTERN est présent.')
search.add_argument('-d', '--dhcp', action='store_true', help='Rechercher les logs concernant les requêtes DHCP')
search.add_argument('-r', '--radius', action='store_true', help='Rechercher les logs concernant les requêtes RADIUS')
search.add_argument('-f', '--filaire', action='store_true', help='Rechercher les logs concernant le filaire')
search.add_argument('-W', '--wifi', action='store_true', help='Rechercher les logs concernant le wifi')
search.add_argument('-M', '--mac', metavar='MACADDR', type=str, default=None, help='Rechercher les logs concernant la mac MACADDR')
search.add_argument('-I', '--ip', metavar='IPADDR', type=str, default=None, help='Rechercher les logs concernant l\'ip IPADDR')
search.add_argument('-p', '--prise', metavar='PRISE', type=str, default=None, help='Rechercher les logs concernant la prise PRISE')
search.add_argument('-a', '--archived', metavar='N', type=int, default=0, help='Rechercher dans les anciens logs (vieux de N jours)')
args = parser.parse_args()
if args.source not in LOGFILES:
print('SOURCE doit être choisi parmi', ', '.join(list(LOGFILES.keys())), file=sys.stderr)
exit(1)
args.source = LOGFILES[args.source]
if args.archived:
args.source += '.{}.gz'.format(args.archived)
if args.mac is None and args.ip is None and args.pattern is None and args.type == 'file':
parser.print_help()
exit(1)
elif args.mac is None and args.ip is None and args.pattern is None and args.type == 'live':
exit(os.system('tail -f {}'.format(args.source)))
filters = []
if not args.pattern:
args.extended_regexp = True
args.ignore_case = True
if not args.filaire and not args.wifi:
if args.dhcp:
filters.append('dhcpd')
if args.radius:
filters.append('freeradius')
elif args.filaire:
if args.dhcp:
filters.append('dhcpd.*'+FIL_NETS)
if args.radius:
filters.append(r'(\(fil\)|NAS:.'+SWITCHES_NETS+')')
elif not args.dhcp:
filters.append(FIL_NETS)
elif args.wifi:
if args.dhcp:
filters.append('dhcpd.*'+WIFI_NETS)
if args.radius:
filters.append(r'"(\(wifi\)|NAS:.'+BORNES_NETS+')')
elif not args.dhcp:
filters.append(WIFI_NETS)
if args.mac:
m = re.fullmatch(MAC_REGEX, args.mac)
if m:
filters.append('[:-]?'.join(m.group(i) for i in range(1, 7)))
else:
print('MAC invalide :', args.mac, file=sys.stderr)
if args.ip:
if re.fullmatch(IPv4_REGEX, args.ip) or re.fullmatch(IPv6_REGEX, args.ip):
filters.append(args.ip)
else:
print('IP invalide :', args.ip, file=sys.stderr)
if args.prise:
if re.fullmatch(PRISE_REGEX, args.prise):
filters.append(r'bat{}-{}\.switches\.crans\.org.*port {}'.format(args.prise[0].lower(), args.prise[1], args.prise[2:4]))
else:
print('Prise invalide :', args.prise, '\nUne prise doit être au format <lettre du bâtiment><n° du switch><port>, par exemple A012 pour avoir le port 12 de bata-0.')
if not filters:
print('Aucun pattern à filtrer', file=sys.stderr)
print('Utilisez --help pour afficher l\'aide.', file=sys.stderr)
exit(1)
args.pattern = '(' + '|'.join(filters) + ')'
grep_args = []
for arg in GREP_ARGS:
if getattr(args, arg):
grep_args.append('--{}'.format(arg.replace('_', '-')))
for arg in GREP_VALUE_ARGS:
if getattr(args, arg):
grep_args.append('-{}'.format(GREP_VALUE_ARGS[arg]))
grep_args.append(getattr(args, arg))
grep_args.append(args.pattern)
if args.type == 'live':
os.system('tail -f {} | grep {}'.format(args.source, ' '.join([shlex.quote(arg) for arg in grep_args])))
elif args.type == 'file':
subprocess.run(['grep'] + grep_args + [args.source])
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment