'''
1、查
输入:www.oldboy.org
获取当前backend下的所有记录
2、新建
输入:
arg = {
'bakend': 'www.oldboy.org',
'record':{
'server': '100.1.7.9',
'weight': 20,
'maxconn': 30
}
}
3、删除
输入:
arg = {
'bakend': 'www.oldboy.org',
'record':{
'server': '100.1.7.9',
'weight': 20,
'maxconn': 30
}
}
复制代码
复制代码
global
log 127.0.0.1 local2
daemon
maxconn 256
log 127.0.0.1 loca
'''
import string, re
def search_backend(*args):
with open(args[0],"r") as f:
server_line = f.readline()
# print(server_line)
regex="bakend {}".format(args[1])
while (regex not in server_line and server_line):
# print(server_line)
server_line=f.readline()
# print(server_line)
if (args[1] in server_line):
server_line = f.readline().strip()
while(server_line):
print(server_line)
server_line = f.readline().strip()
# print(server_line.strip())
# break
def create_backend(filename,backend_dict_string):
with open(filename,"a+") as f:
backend=eval(backend_dict_string)
f.write("\n\nbackend"+" "+backend["bakend"])
f.write("\n\t\tserver" + " " + backend["record"]["server"]+" "+backend["record"]["server"]+" weight "+str(backend["record"]["weight"])+ \
" maxconn " + str(backend["record"]["maxconn"]))
def delete_backend(filename,bakend):
bakend=eval(bakend)
with open(filename,"r+") as fr:
readfile=fr.readlines()
regex1="backend {}".format(bakend["bakend"])
regex2="server {} {} weight {} maxconn {}".format(bakend["record"]["server"],\
bakend["record"]["server"],\
bakend["record"]["weight"],\
bakend["record"]["maxconn"])
print(regex1)
print(regex2)
line_content=[]
for line in readfile:
if re.match(regex1, line) or re.search(regex2, line):
continue
line_content.append(line)
fr.seek(0)
fr.truncate(0)
fr.writelines(line_content)
def man():
choice=1
while(choice):
choice=input("输入1 2 3,1 查询bakend 2 增加bakend 3 删除bakend:")
if choice=="1":
web_id=input("查询主机名:")
search_backend("haproxy.conf",web_id)
elif choice=="2":
dict_bakend=input("输入增加的bakend eg:{'bakend': 'www.oldboy.org', 'record': {'server': '100.1.7.9', 'weight': 20, 'maxconn': 30}}:")
create_backend("haproxy.conf",dict_bakend)
else:
bakend_delete = input("输入删除的bakend eg:{'bakend': 'www.oldboy.org', 'record': {'server': '100.1.7.9', 'weight': 20, 'maxconn': 30}}:")
delete_backend("haproxy.conf",bakend_delete)
if __name__ == '__main__':
man()
正则匹配还是不怎会用