#!/user/bin/python
# -*- coding:utf-8 -*-
#定义查询功能
def fetch(data):
print("\033[1;43m这是查询功能\033[0m")
print("\033[1;43m用户数据是\033[0m",data)
backend_data = "backend %s" %data
with open("haproxy.conf","r") as read_f :
#tag用来表示状态
tag = False
ret = []
for read_line in read_f:
if read_line.strip() == backend_data:
tag = True
continue
if tag and read_line.startswith("backend"):
break
if tag :
print("\033[1;45m%s\033[0m" %read_line,end= "")
ret.append(read_line)
return ret
def add():
pass
def change(data):
print("这是修改功能")
print("用户输入的数据是",data)
backend = data[0]["backend"] #定义data0是要修改的记录、data0是字典的形式,再加["backend"]根据key取value值也就是www.oldboy1.org并且再返回定义backend
backend_data = "backend %s" %backend
old_server_record = "%sserver %s %s weight %s maxconn %s\n" %(" "* 8,data[0]["record"]["server"],
data[0]["record"]["server"],
data[0]["record"]["weight"],
data[0]["record"]["maxconn"])
new_server_record = "%sserver %s %s weight %s maxconn %s\n" %(" "* 8,data[1]["record"]["server"],
data[1]["record"]["server"],
data[1]["record"]["weight"],
data[1]["record"]["maxconn"])
print("用户想要修改的记录是",old_server_record)
res = fetch(backend) #执行查询的操作调fetch函数并且再传入上面取得backend作为参数并且再返回定义res
print("来自change函数--",res)
if not res or old_server_record not in res:
return "你要修改的记录不存在"
else:
index = res.index(old_server_record)
res[index] = new_server_record
with open("haproxy.conf","r") as read_f,\
open("haproxy.conf_new","w") as write_f :
tag = False
for read_line in read_f:
if read_line.strip() == backend_data:
tag = True
continue
if not tag:
write_f.write(read_line)
else:
for record in res:
write_f.write(record)
def delete():
pass
if __name__ == '__main__':
msg = """
1: 查询,
2 : 增加,
3 : 修改,
4 : 删除,
5 : 退出
"""
msg_dic = {
"1" : fetch,
"2" : add,
"3" : change,
"4" : delete
}
while True:
print(msg)
choice = input("请输入选项:").strip()
if not choice : continue
if choice == "5" : break
data = input("请输入用户数据:").strip()
if choice != "1" :
data = eval(data) #把传入的字符串进行提取出来
res = msg_dic[choice](data)
print("最终结果是-->",res)
#定义原纪录和修改后的记录
# [{"backend" : "www.oldboy1.org" , "record" : {"server" : "2.2.2.4" , "weight" : 20,"maxconn" : 3000 }},{"backend" : "www.oldboy1.org","record" : {"server" : "2.2.2.5","weight": 30,"maxconn":4000}}]