Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- """
- Log Anonymizer reads a logfile, where the first field must be a valid IPv4
- or IPv6 address. It anonymizes 16 bits with IPv4 addresses and
- 32 bits with IPv6 addresses.
- If required the ip address could be hashed.
- It is more anonymized if you use the random generated token.
- By default the file is not overwritten.
- If you use the command without -o, then the anonymized logfile
- is printed to console.
- """
- import os
- import ipaddress
- import hashlib
- import secrets
- import argparse
- import sys
- from pathlib import Path
- def log_anonymizer(log: Path, hash_ip: bool=True, salt: bool=True):
- def anonymize(ip, ipv4_mask=16, ipv6_mask=32):
- ip = ipaddress.ip_address(ip)
- mask = 2 ** ip.max_prefixlen - 1
- if ip.version == 4:
- mask -= 2 ** ipv4_mask - 1
- elif ip.version == 6:
- mask -= 2 ** ipv6_mask - 1
- return ipaddress.ip_address(int(ip) & mask)
- if salt:
- salt_val = secrets.token_hex()
- with open(log) as fd:
- for idx, line in enumerate(fd, start=1):
- try:
- ip, rest = line.strip().split(maxsplit=1)
- except ValueError:
- print("Error with line no {}".format(idx), file=sys.stderr)
- yield line.strip()
- continue
- try:
- ip = str(anonymize(ip))
- except ValueError:
- print("Could not parse ip in line no {}".format(idx), file=sys.stderr)
- yield line.strip()
- continue
- if salt:
- ip += salt_val
- if salt or hash_ip:
- ip = hashlib.sha256(ip.encode()).hexdigest()
- yield " ".join((ip, rest))
- if __name__ == "__main__":
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("logfile", type=Path, help="Logfile to anonymize")
- parser.add_argument("-H", action="store_true", help="hash ip address with sha256 after anonymize")
- parser.add_argument("-s", action="store_true", help="Add random salt before hashing")
- parser.add_argument("-o", action="store_true", help="Overwrite file.")
- args = parser.parse_args()
- log = log_anonymizer(args.logfile, args.H, args.s)
- if args.o:
- new_name = args.logfile.name + ".anon"
- new_file = args.logfile.with_name(new_name)
- with new_file.open("w") as fd:
- for line in log:
- fd.write(line + os.linesep)
- new_file.rename(args.logfile)
- else:
- for line in log:
- print(line)
Add Comment
Please, Sign In to add comment