繁体   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