Python脚本中的IPv4地址替换

时间:2013-11-26 18:50:36

标签: python regex python-2.6

我无法让这个工作,我希望有任何想法:

我的目标:获取一个文件,逐行读取,用任何IP地址替换特定替代品,并将更改写入同一文件。

我知道这不是正确的语法

伪示例:

$ cat foo
10.153.193.0/24 via 10.153.213.1

def swap_ip_inline(line):
  m = re.search('some-regex', line)
  if m:
    for each_ip_it_matched:
      ip2db(original_ip)
    new_line = reconstruct_line_with_new_ip()

    line = new_line

  return line

for l in foo.readlines():
  swap_ip_inline(l)

do some foo to rebuild the file.

我想取文件'foo',找到给定行中的每个IP,用ip2db函数替换ip,然后输出更改的行。

工作流: 1.打开文件 2.读行 3.交换IP 4.将行(已更改/未更改)保存到tmp文件中 5.使用tmp文件覆盖原始文件

*编辑添加伪代码示例

2 个答案:

答案 0 :(得分:1)

你走了:

>>> import re
>>> ip_addr_regex = re.compile(r'\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b')
>>> f = open('foo')
>>> for line in f:
...     print(line)
...
10.153.193.0/24 via 10.153.213.1

>>> f.seek(0)
>>>

specific_substitute = 'foo'

>>> for line in f:
...     re.sub(ip_addr_regex, specific_substitute, line)
...
'foo/24 via foo\n'

答案 1 :(得分:0)

此链接为我提供了我正在寻找的呼吸:

Python - parse IPv4 addresses from string (even when censored)

一个简单的修改通过了初始烟雾测试:

def _sub_ip(self, line):
    pattern = r"((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)([ (\[]?(\.|dot)[ )\]]?(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})"
    ips = [each[0] for each in re.findall(pattern, line)]
    for item in ips:
        location = ips.index(item)
        ip = re.sub("[ ()\[\]]", "", item)
        ip = re.sub("dot", ".", ip)
        ips.remove(item)
        ips.insert(location, ip)

    for ip in ips:
        line = line.replace(ip, self._ip2db(ip))

    return line

我确信我会在路上清理它,但这是一个很好的开始。

相关问题