日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

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

作者:allway2 ? 更新時間: 2022-09-19 編程語言

讓我們看看如何使用 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元素。

總結

原文鏈接:https://blog.csdn.net/allway2/article/details/122548538

欄目分類
最近更新