【问题标题】:IPv4 address substitution in Python scriptPython 脚本中的 IPv4 地址替换
【发布时间】:2013-12-12 02:12:41
【问题描述】:

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

我的目标:获取一个文件,逐行读取,将任何 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文件覆盖原文件

*编辑添加伪代码示例

【问题讨论】:

标签: python regex python-2.6


【解决方案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'

【讨论】:

  • ssheth,这与我所拥有的相似。我遇到的问题是我需要在 sub 之前运行匹配,以便我可以评估给定行中的 IP 地址。我想对给定 IP 地址的每次出现进行 1:1 替换,但我不知道该怎么做。我已经尝试了上面的内容,并且尝试使用 .split() 和 re.search.groups() 拆分每一行,如果没有的话,我无法将正则表达式细化到只给我 IP 地址周围的空间等。如果我可以将一个组调用到 re.sub 的替代函数中,那就是它。这有意义吗?
【解决方案2】:

这个链接给了我我一直在寻找的突破:

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

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

【讨论】:

    猜你喜欢
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 2011-02-16
    • 1970-01-01
    • 2017-11-27
    • 2012-12-25
    • 1970-01-01
    相关资源
    最近更新 更多