从文件中的匹配字符串读取行。。python

2024-09-30 08:16:46 发布

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

我有一个脚本,从F5配置文件打印池名称。。我想在多个F5配置文件上运行这个。。我想能够从^池| ^}(池或}开始行)。。。现在我得到了我想要的输出,因为我告诉脚本从第2348行读取。。在

我想消除在xrange(2348)中使用I,因为其他文件F5配置文件更小。。在

它的工作方式是让脚本开始逐行读取^pool或^}中的文件
当前脚本:

import re
seenrule = 'false'

File = open("/home/t816874/F5conf/unzip/config/bigip.conf", "r")
for i in xrange(2348):
        File.next()

for line in File:
        if re.match("(^pool p)", line, re.IGNORECASE):
                a = line.lstrip("pool p")
                ONE = a[:-2]
                print "Pool Name:", ONE

        if re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d] {1,3})', line):
               if seenrule == 'false':
                       x = line.lstrip("members ")
                       print x

if re.match("(^rule )", line):
        seenrule = 'true'

---------------------------------------------------------------在

我的尝试:

^{pr2}$

谢谢你们的帮助!在

-----------在

conf文件类似于:

node 172.0.0.0 {
   screen ab2583-1.2
}
node 172.0.0.1 {
   screen ab2583-1.3
}
node 172.0.0.3 {
   screen ab2584-1.2
}
pool pWWW_abcd_HTTPS {
   lb method member predictive
   monitor all mWWW_staging.telecom_TCP
   members {
      0.0.0.0:8421 {}
      0.0.0.1:18431 {
         session user disabled
      }
      0.0.0.2:8421 {}
      0.0.0.3:18431 {
         session user disabled
      }
   }
}
pool pWWW_vcm2APP.defg_HTTP {
   lb method member predictive
   monitor all mWWW_vcm2APP.defg_TCP
   members 0.0.0.5:27110 {}
}
node..
....
.

Tags: 文件re脚本nodefalseif配置文件line
1条回答
网友
1楼 · 发布于 2024-09-30 08:16:46

你想要什么还不完全清楚,不过我来猜猜看。您正在尝试为每个池获取成员。你没有提到任何关于seenrule的事情,所以我把它忘了。在

如果您不想解析此数据结构,并且如果顶级块总是以'}\n'行结束,则可以执行以下操作:

import re
f = open('/home/t816874/F5conf/unzip/config/bigip.conf', 'r')

# Iterate over lines.
for line in f:
    # If pool block is met.
    if line.startswith('pool p'):
        pname = line.split()[1]
        pmembers = []
        # Iterate over block.
        # Block is expected to be terminated by line '}\n'.
        for pline in iter(lambda: next(f), '}\n'):
            members = re.findall(r'\d{1,3}(?:\.\d{1,3}){3}:\d{1,5}', pline)
            pmembers.extend(members)

        print(pname, pmembers)

f.close()

输出:

^{pr2}$

相关问题 更多 >

    热门问题