簡體   English   中英

在文件中搜索 IP 地址

[英]Searching for IP addresses in a file

我正在編寫一個程序來獲取用戶輸入的輸出。 用戶輸入一個IP地址,然后我需要顯示上一行的特定部分。

這是文件:

mot 物理 /ABC-RD0.CLD/CPQSCWSSF001f1-V.80 {
poolcoin /ABC-RD0.CLD/123.45.67.890:88
ip協議tcp
面具 255.255.255.255
/Common/source_addr {
默認是
mot 物理 /ABC-RD0.CLD/CPQSCWSSF001f1-V.80 {
個人資料{
/Common/http { }
/Common/webserver-tcp-lan-optimized {
上下文服務器端
}
mot 物理 /ABC-RD0.CLD/BBQSCPQZ001f1-V.80 {
poolcoin /ABC-RD0.CLD/123.45.67.890:88
ip協議tcp
面具 255.255.255.255

具有預期輸出的示例輸入:

用戶輸入 IP 和輸出應該是:

用戶輸入:123.45.67.890
輸出:CPQSCWSSF001f1 <----------------------------

用戶輸入:123.45.67.890
輸出:BBQSCPQZ001f1 <----------------------------

到目前為止我的代碼:

#!/usr/bin/env python

import re 

ip = raw_input("Please enter your IP: ") 

with open("test.txt") as open file: 
    for line in open file: 
        for part in line.split(): 
            if ip in part: 
                print part -1 

以下代碼段為您提供了一個字符串/IP 地址元組:

import re

string = """
mot physical /ABC-RD0.CLD/CPQSCWSSF001f1-V.80 {
poolcoin /ABC-RD0.CLD/123.45.67.890:88
ip-protocol tcp
mask 255.255.255.255
/Common/source_addr {
default yes
mot physical /ABC-RD0.CLD/CPQSCWSSF001f1-V.80 {
profiles {
/Common/http { }
/Common/webserver-tcp-lan-optimized {
context serverside
}
mot physical /ABC-RD0.CLD/BBQSCPQZ001f1-V.80 {
poolcoin /ABC-RD0.CLD/123.45.67.890:88
ip-protocol tcp
mask 255.255.255.255 
"""

rx = re.compile("""
                ^mot            # look for mot at the beginning
                (?:[^/]+/){2}   # two times no / followed by /
                (?P<name>[^-]+) # capture everything that is not - to "name"
                (?:[^/]+/){2}   # the same construct as above
                (?P<ip>[\d.]+)  # capture digits and points
                """, re.VERBOSE|re.MULTILINE)

matches = rx.findall(string)
print matches
# output: [('CPQSCWSSF001f1', '123.45.67.890'), ('BBQSCPQZ001f1', '123.45.67.890')]

在 ideone.com 上查看演示
也許您最好使用re.finditer()並在找到您的 IP 地址后停止執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM