在fi中搜索IP地址

2024-09-29 18:53:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个程序来获取用户输入的输出。用户输入一个IP地址,然后我需要显示上述行的特定部分。你知道吗

文件如下:

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

具有预期输出的示例输入:

User inputs the IP and output should be:

user input: 123.45.67.890
output: CPQSCWSSF001f1 <----------------------------

user input: 123.45.67.890
output: 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 

Tags: 用户inipinputoutputcommonopentcp
1条回答
网友
1楼 · 发布于 2024-09-29 18:53:45

以下代码段提供了字符串/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')]

a demo on ideone.com
也许您最好使用re.finditer()并在找到ip地址后停止执行。你知道吗

相关问题 更多 >

    热门问题