(Sep-06-2019, 03:17 PM)DeaD_EyE Wrote: Usestr.join
My output:
Yep thanks .. I understand that he "." means any char. The App Im pasting into recognizes an ip just so long its wrapped in ^$.
Output:deadeye@nexus ~ $ python2.7 parse_ips.py Without piping to program, you have to use --input-file deadeye@nexus ~ $ python2.7 parse_ips.py --input-file usage: parse_ips.py [-h] [--input-file INPUT_FILE] parse_ips.py: error: argument --input-file: expected one argument deadeye@nexus ~ $ python2.7 parse_ips.py --input-file hosts.txt ^10\.10\.10\.10$|^10\.10\.10\.11$|^10\.10\.10\.12$|^10\.10\.10\.13$|^10\.10\.10\.14$ deadeye@nexus ~ $ cat hosts.txt | python2.7 parse_ips.py ^10\.10\.10\.10$|^10\.10\.10\.11$|^10\.10\.10\.12$|^10\.10\.10\.13$|^10\.10\.10\.14$
Thanks.
Code:
#!/usr/bin/env python2.7 from __future__ import print_function import sys import argparse def ip2regex(text): ips = [] for row in text.splitlines(): try: ip, hostname = row.split() except ValueError: # skip errors continue ip = '^' + ip.replace('.', r'\.') + '$' ips.append(ip) return '|'.join(ips) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--input-file', required=False, help='Input file to generate regex output.') args = parser.parse_args() if args.input_file is None and not sys.stdin.isatty(): print(ip2regex(sys.stdin.read())) elif args.input_file and sys.stdin.isatty(): with open(args.input_file) as fd: print(ip2regex(fd.read())) else: print('Without piping to program, you have to use --input-file', file=sys.stderr)Line 15-17 preparing the IP address. By the way, a dot is a metachar in regex. The dot stands for any kind of char.
If you use the dot without escaping it, the regex^10.10.10.10$
will be also match:10510710310
PS:split
is the opposite ofjoin
.
Ive seen this construct in some example code .. but not in any instruction .... probably because Im just starting out.
What is it called and where can I learn about it ..
ips = [ip_addr for line in f for ip_addr, *_ in line.split()]