Python帮助从文本文件中获取IP地址范围,然后输出该范围内的每个IP地址

标签 python linux parsing

到目前为止,程序接收了一个目录中的所有文本文件,然后将它们输出到一个同名但后缀为.out 的文件中。如果有一个 ip 地址 1992.168.1.1-192.168.1.7 我希望它输出该范围内的所有 ips 到新文件名。

#!/usr/bin/env python

import sys
import re
import os

try:
    if file.endswith (".txt"):
    f=open(file, 'r')
try:
    file = open(f, "r")
    ips = []
    for text in file.readlines():
       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:
        #name of the file
        name = os.path.splitext() [0]
        name = name +".out"
       outfile = open(name, 'w')
       spider = "".join(ip)
       if spider is not '':
          outfile.write(spider)
          outfile.write("\n")
finally:
    file.close()
    outfile.close()
except IOError, (errno, strerror):
    print "I/O Error(%s) : %s" % (errno, strerror)

最佳答案

如果您使用的是 Python 3.3+,请使用 ipaddress模块:

>>> for addr in IPv4Network('192.0.2.0/28'):
...   addr
...
IPv4Address('192.0.2.0')
IPv4Address('192.0.2.1')
IPv4Address('192.0.2.2')
IPv4Address('192.0.2.3')
IPv4Address('192.0.2.4')
IPv4Address('192.0.2.5')
IPv4Address('192.0.2.6')
...
IPv4Address('192.0.2.15')

关于Python帮助从文本文件中获取IP地址范围,然后输出该范围内的每个IP地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24497588/

相关文章:

python - 单击时的 Webdriver WebDriverException/TimeoutException

python - 中止 Python 脚本会损坏打开读取的文件吗?

linux - 在 ubuntu 版本 18.04 LTS 上安装 mongodb 时遇到问题

regex - sed - 如何使用 sed 进行正则表达式组

html - 常规 : parsing xml with HTML tags inside

python - 递归拆分函数

linux - "echo -e"在 su -c 命令中不起作用

string - 在 Perl 中解析 A​​pache 日志

c - 使用 getopt 在 C 中解析参数

python - 使 _tkinter.createfilehandler 再次工作(或提供解决方法)