#Author:ZhaoBin
#实现对Haproxy配置文件的增删改查
def fetch(backend):
result = []
with open(‘ha.conf‘,‘r‘,encoding=‘utf-8‘) as f:
flag = False
for line in f:
if line.strip().startswith("backend") and line.strip() == "backend " + backend:
flag = True
continue
if flag == True and line.strip().startswith("backend"):
flag = False
break
if flag == True and line.strip():
result.append(line.strip())
return result
def add(backend,record):
#先检查记录是否存在
record_list=fetch(backend)
print(record_list)
if not record_list:
#backend不存在
with open("ha.conf","r") as old, open("new.conf","w") as new:
for line in old:
new.write(line)
new.write("\nbackend " + backend+"\n")
new.write(" "*8 + record+"\n")
else:
#backend存在,record也存在
if record in record_list:
pass
else:
#backend存在,record不存在
record_list.append(record)
with open("ha.conf", "r") as old, open("new.conf", "w") as new:
flag = False
for line in old:
if line.strip().startswith("backend") and line.strip() == "backend " + backend:
flag = True
new.write(line)
for new_line in record_list:
new.write(" "*8+ new_line + "\n")
if flag and line.strip().startswith("backend"):
flag = False
new.write(line)
continue
if not flag and line.strip():
new.write(line)
#ret = fetch("www.oldboy.org")
# print(ret)
bk="www.oldboy.org"
rd="server 100.1.7.8 weight 10 maxconn 3000"
add(bk,rd)