![](/img/trans.png)
[英]How to read the string from an .INI file and then read that string from a text file and print the entire line using Python?
[英]read line from match string in file .. python
我有一個從F5配置文件打印池名稱的腳本。我想在多個F5配置文件上運行此腳本。.我希望能夠從^ pool | ^}中讀取(pool OR}使行開始)。 ..目前,我告訴腳本從第2348行讀取時,我得到了所需的輸出。
我想消除xrange(2348)中i的使用,因為其他文件F5配置文件較小。
它的工作方式是,如果我讓腳本開始從^ pool OR ^}逐行讀取文件
當前腳本:
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'
我的嘗試:
import re
seenrule = 'false'
startline = 'false'
File = open("/home/t816874/F5conf/unzip/config/bigip.conf", "r")
if re.match("(^pool|^})", line):
startline = 'true'
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'
感謝您的幫助!
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..
....
.
目前尚不清楚您想要什么,但我會盡力猜測。 您正在嘗試獲取每個池的成員。 您沒有提及任何關於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()
輸出:
pWWW_abcd_HTTPS ['0.0.0.0:8421', '0.0.0.1:18431', '0.0.0.2:8421', '0.0.0.3:18431']
pWWW_vcm2APP.defg_HTTP ['0.0.0.5:27110']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.