简体   繁体   中英

IPv4 address substitution in Python script

I'm having trouble getting this to work, and I am hoping for any ideas:

My goal: to take a file, read it line by line, substitute any IP address for a specific substitute, and write the changes to the same file.

I KNOW THIS IS NOT CORRECT SYNTAX

Pseudo-Example:

$ 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.

I want to take the file 'foo', find each IP in a given line, substitute the ip using the ip2db function, and then output the altered line.

Workflow: 1. Open File 2. Read Lines 3. Swap IP's 4. Save lines (altered/unaltered) into tmp file 5. Overwrite original file with tmp file

*edited to add pseudo-code example

Here you go:

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

This link gave me the breatkthrough I was looking for:

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

a simple modification passes initial smoke tests:

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

I'm sure I'll clean it up down the road, but it's a great start.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM