如何在命令行管道中匹配IPv6地址



如何制作一个在stdin中查找IPv6地址的shell命令?

一种选择是使用:

grep -Po '(?<![[:alnum:]]|[[:alnum:]]:)(?:(?:[a-f0-9]{1,4}:){7}[a-f0-9]{1,4}|(?:[a-f0-9]{1,4}:){1,6}:(?:[a-f0-9]{1,4}:){0,5}[a-f0-9]{1,4})(?![[:alnum:]]:?)'

这个RE是基于"匹配有效IPv6地址的正则表达式"的思想,但这并不完全准确。我可以使用一个更丑陋的正则表达式,但有没有更好的方法,一些我不知道的命令?

由于我找不到使用shell脚本命令的简单方法,我在Python中创建了自己的命令:

#!/usr/bin/env python
# print all occurences of well formed IPv6 addresses in stdin to stdout. The IPv6 addresses should not overlap or be adjacent to eachother. 
import sys
import re
# lookbehinds/aheads to prevent matching e.g. 2a00:cd8:d47b:bcdf:f180:132b:8c49:a382:bcdf:f180
regex = re.compile(r'''
            (?<![a-z0-9])(?<![a-z0-9]:)
            ([a-f0-9]{0,4}::?)([a-f0-9]{1,4}(::?[a-f0-9]{1,4}){0,6})?
            (?!:?[a-z0-9])''', 
        re.I | re.X)
for l in sys.stdin:
    for match in regex.finditer(l):
        match = match.group(0)
        colons = match.count(':')
        dcolons = match.count('::')
        if dcolons == 0 and colons == 7:
            print match
        elif dcolons == 1 and colons <= 7:
            print match

最新更新