拆分最后一个八位字节的IP地址的麻烦

时间:2013-06-07 16:11:46

标签: python

我无法将最后一个八位字节从我的IP地址拆分并将结果打印到文件中。

这是当前的输出

IN    PTR   10.102.36.38.
IN    PTR   .
IN    PTR   192.168.100.11.
IN    PTR   192.168.100.12.

这是要写入文件的所需输出。

38   IN    PTR   10.102.36.38.
( deleted  this line ) IN    PTR   .
11   IN    PTR   192.168.100.11.
12   IN    PTR   192.168.100.12.

#!/usr/bin/env python
import sys
import re
from subprocess import call

try:
    if sys.argv[1:]:
        print "File: %s" % (sys.argv[1])
        yamlfile = sys.argv[1]
    else:
        yamlfile = raw_input("Please enter the yaml server file to  parse, e.g /etc/puppet/hieradata/*.yaml: ")
    try:
        file = open(yamlfile, "r")
        ips = []
        for text in file.readlines():
           text = text.rstrip()
           regex = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})$',text)
           if regex is not None and regex not in ips:
               ips.append(regex)

        for ip in ips:
           outfile = open("/tmp/blocked_ips_test", "a")
#           addy = "".join(ip)
           #octet = call("cut", "-d.", "-f4")
           addy = 'IN    PTR'   '.'.join(reversed(ip)) + "."
           #addy = '.'.join(reversed(ip)) + "."
           #addy = '.'.join(reversed(ip)) + ".in-addr.arpa."
           if addy is not '':
              print  "IN    PTR   %s " % (addy)
              #print "IN    PTR   %s " % (addy) >>outfile

              outfile.write(addy)
              outfile.write("\n")
    finally:
        file.close()
        outfile.close()
except IOError, (errno, strerror):
        print "I/O Error(%s) : %s" % (errno, strerror)

2 个答案:

答案 0 :(得分:0)

import sys
import re

if len(sys.argv) > 1:
    yamlfile = sys.argv[1]
else:
    yamlfile = raw_input("Please enter the yaml server file to  parse, e.g /etc/puppet/hieradata/*.yaml: ")

with open(yamlfile) as infile:
    with open("/tmp/blocked_ips_test", "a") as outfile:
        ips = set()
        for text in infile:
            text = text.rstrip()
            matched = re.search(r'(\d{,3}\.){3}\d{,3}', text)
            if matched:
                ips.add(matched.group())

        for ip in ips:
            line = '%s    IN    PTR   %s.' % (ip.rsplit('.', 1)[-1], ip)
            print line
            print >>outfile, line

答案 1 :(得分:0)

类似的东西可以解决问题(Python 2& 3):

import re

r = re.compile(r'^IN\s+PTR\s+([\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.([\d]{1,3})\.)\s*$')

with open("my.zone", "rt") as file:
    for line in file:
        m = r.match(line)
        if m:
            print("{1} IN PTR {0}".format(*m.groups()))

将您的源数据放在“my.zone”中:

sh$ cat my.zone
IN    PTR   10.102.36.38.
IN    PTR   .
IN    PTR   192.168.100.11.
IN    PTR   192.168.100.12.

这会产生以下结果(静默删除不匹配的行):

38 IN PTR 10.102.36.38.
11 IN PTR 192.168.100.11.
12 IN PTR 192.168.100.12.