在文件中搜索IP地址

时间:2016-03-06 07:29:57

标签: python regex python-2.7 python-3.x

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

这是文件:

  

mot physical /ABC-RD0.CLD/CPQSCWSSF001f1-V.80 {
      poolcoin /ABC-RD0.CLD/123.45.67.890:88
      ip-protocol tcp
      面具255.255.255.255
          / Common / source_addr {
              default yes
mot physical /ABC-RD0.CLD/CPQSCWSSF001f1-V.80 {
      个人资料{
          / Common / http {}
          / Common / webserver-tcp-lan-optimized {
              context contextide}} mot physical /ABC-RD0.CLD/BBQSCPQZ001f1-V.80 {
      poolcoin /ABC-RD0.CLD/123.45.67.890:88
      ip-protocol 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 

1 个答案:

答案 0 :(得分:0)

以下代码段为您提供了一个字符串/ 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地址后停止执行。