教你使用Python从文件中提取IP地址

2022-07-27 12:03:50
目录
算法 :  代码输出 :代码:输出 :补充:python提取一段字符串中的ip地址总结

让我们看看如何使用 Python 从文件中提取 IP 地址。

算法>
    为正则表达式导入 re 模块。使用 open() 函数打开文件。读取文件中的所有行并将它们存储在列表中。声明 IP 地址的模式。正则表达式模式是: 
    r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
      对于列表中的每个元素,使用 search() 函数搜索模式,将 IP 地址存储在列表中。显示包含 IP 地址的列表。

      要处理的文件是 test.txt : 

      test.txt

      代码

      # importing the module
      import re
       
      # opening and reading the file
      with open('f:/test.txt', encoding='utf-8') as fh:
          fstring = fh.readlines()
       
      # declaring the regex pattern for IP addresses
      pattern = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')
       
      # initializing the list object
      lst = []
       
      # extracting the IP addresses
      for line in fstring:
          match = pattern.search(line)
          if match is not None:
              lst.append(match[0])
          else:
              lst.append(None)
       
      # displaying the extracted IP addresses
      print(lst)

      输出>

      上面的 Python 程序显示文件中存在的任何类型的 IP 地址。我们还可以显示有效的IP 地址。

      有效 IP 地址的规则: 

        数字应在 0-255 范围内它应该由 4 个以“.”分隔的单元格组成。

        有效 IP 地址的正则表达式是:

        ((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5] |2[0-4][0-9]|[01]?[0-9][0-9]?)

        用于有效 IP 的正则表达式说明:

        由于我们不能在正则表达式中使用 0-255 范围,我们将其分为 3 组:

          25[0-5] - 表示从 250 到 255 的数字2[0-4][0-9] – 表示从 200 到 249 的数字[01]?[0-9][0-9]?- 表示从 0 到 199 的数字

          要处理的文件是 test2.txt : 

          000.0000.00.00
          192.168.1.1
          912.465.123.123
          192.168.4.164
          69.168.4.226
          32.89.31.164
          67.168.3.227

          代码:

          # importing the module
          import re
           
          # opening and reading the file
          with open('test2.txt', encoding='utf-8') as fh:
              string = fh.readlines()
           
          # declaring the regex pattern for IP addresses
          pattern = re.compile('''((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)''')
           
          # initializing the list objects
          valid = []
          invalid = []
           
          # extracting the IP addresses
          for line in string:
              line = line.rstrip()
              result = pattern.search(line)
           
              # valid IP addresses
              if result:
                  valid.append(line)
           
              # invalid IP addresses
              else:
                  invalid.append(line)
           
          # displaying the IP addresses
          print("Valid IPs")
          print(valid)
          print("Invalid IPs")
          print(invalid)

          输出>

          "C:\Program Files\Python39\python.exe" C:/Users/Administrator/PycharmProjects/pythonProject8/ExtractIP2.py
          Valid IPs
          ['192.168.1.1', '192.168.4.164', '69.168.4.226', '32.89.31.164', '67.168.3.227']
          Invalid IPs
          ['000.0000.00.00', '912.465.123.123']
           
          进程已结束,退出代码为 0

          补充:python提取一段字符串中的ip地址

          代码如下:

          #!/usr/bin/env python3
          # -*- coding:utf-8 -*-
          
          import re
          import os
          
          ip_str = os.popen('cat /root/bin/ips').read()
          ipList = re.findall( r'[0-9]+(?:\.[0-9]+){3}',ip_str)
          print(ipList)

          有时候从上游收到的ip地址很多是夹杂其他字符的,比如逗号,分号,中文字符,英文字符等等,需要提取纯粹的ip地址,可以使用这种方式。已经默认给出的字符串包含的都是正确的ip地址。如果想在确认ip地址是否合法,可以对列表ipList进行遍历,剔除不合法的ip元素。

          总结

          到此这篇关于使用Python从文件中提取IP地址的文章就介绍到这了,更多相关Python提取IP地址内容请搜索易采站长站以前的文章或继续浏览下面的相关文章希望大家以后多多支持易采站长站!