Python脚本中的IPv4地址替换

2024-10-01 11:19:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难让这个工作起来,我希望有什么想法:

我的目标是:获取一个文件,逐行读取,将任何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阅读行 三。交换IP 4将行(已更改/未更改)保存到tmp文件中 5用tmp文件覆盖原始文件

*编辑后添加伪代码示例


Tags: 文件ip示例目标newforfooline
2条回答

给你:

>>> 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'

这个链接给了我想要的答案:

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

我肯定我会把它清理干净的,但这是一个很好的开始。在

相关问题 更多 >