4.作业需求:
(1)根据用户输入输出对应的backend下的server信息
(2) 可添加backend 和sever信息
(3)可修改backend 和sever信息
(4)可删除backend 和sever信息
(5) 操作配置文件前进行备份
(6)添加server信息时,如果ip已经存在则修改;如果backend不存在则创建;若信息与已有信息重复则不操作
1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 # Author:Ahappier
4
5
6 import os,sys
7
8 #将文本生成字典和列表
9 def show_list(file):
10 backend_list=[]
11 backend_dict={}
12 server_list=[]
13 server_dict={}
14 with open (file,"r") as f: #读取haproxy文件
15 for line in f:
16 line =line.strip()
17 if line.startswith("backend") == True: #判断backend是否开头,并写入backend_list内
18 backend_name = line.split()[1]
19 backend_list.append(backend_name)
20 server_list=[]
21 elif line.startswith("server")== True:
22 server_dict["name"]=line.split()[1]
23 server_dict["ip"]=line.split()[2]
24 server_dict["weight"]=line.split()[4]
25 server_dict["maxconn"]=line.split()[6]
26 server_list.append(server_dict.copy())
27 backend_dict[backend_name]=server_list
28 return (backend_list,backend_dict)
29
30 #读取backend的内容
31 def backend_show(backend_list):
32 backend_show_dict={}
33 print("backend列表信息如下")
34 for index,k in enumerate(backend_list,1):
35 print(index,k)
36 backend_show_dict[str(index)]=k
37 return backend_show_dict
38
39 #读取server内容
40 def server_show(backend_input,backend_dict):
41 server_show_dict={}
42 server_list=backend_dict[backend_input]
43 for i,k in enumerate(server_list,1):
44 print(i,"name:",k["name"],"\tip:",k["ip"],"\tweight:",k["weight"],"\tmaxconn:",k["maxconn"])
45 server_show_dict[i]=k
46 return server_show_dict
47
48 #显示操作编号和列表
49 def action_list():
50 print("****************************************")
51 print("\t\t欢迎来到haproxy操作平台")
52 print("****************************************")
53 print('''
54 1.查询backend和server信息
55 2.添加backend和server信息
56 3.修改backend和server信息
57 4.删除backend和server信息
58 5.退出
59 ''')
60 print("****************************************")
61 action_num =input("请选择编号(注意是数字):")
62 return action_num
63
64 #定义查询功能
65 def inquiry(inquiry_input):
66 while True:
67 if inquiry_input in backend_show_dict:
68 backend_input = backend_show_dict[inquiry_input]
69 print(backend_input,":")
70 server_show(backend_input,backend_dict)
71 break
72 elif inquiry_input in backend_show_dict.values():
73 print(inquiry_input,":")
74 server_show(inquiry_input,backend_dict)
75 break
76 else:
77 inquiry_input = input("输入错误,请重新输入:")
78
79 #定义添加功能
80 def add(add_input,file):
81 (backend_list,backend_dict)= show_list(file)
82 while True:
83 if add_input in backend_show_dict:
84 add_dict={}
85 add_dict["name"]=input("请输入需要增加的server的名称:")
86 add_dict["ip"]= input("请输入需要增加的server的ip:")
87 add_dict["weight"]= input("请输入需要增加的server的weight:")
88 add_dict["maxconn"]= input("请输入需要增加的server的maxconn:")
89 backend_name_add= backend_list[int(add_input)-1]
90 #如果ip存在,就更新weight和maxconn信息
91 for dict in backend_dict[backend_name_add]:
92 if add_dict["ip"] in dict.values():
93 dict["weight"]=add_dict["weight"]
94 dict["maxconn"]=add_dict["maxconn"]
95 break
96 else:
97 backend_dict[backend_name_add].append(add_dict)
98
99 backup(file,backend_name_add,backend_dict)
100 print("name:%s IP:%s weight:%s manxconn:%s已添加成功"%(
101 add_dict["name"],add_dict["ip"],add_dict["weight"],add_dict["maxconn"]))
102 break
103 else:
104 add_dict={}
105 add_dict["name"]=input("请输入%s下新增的server名称:"%add_input)
106 add_dict["ip"]=input("请输入%s下新增的ip:"%add_input)
107 add_dict["weight"]=input("请输入%s下新增的weight:"%add_input)
108 add_dict["maxconn"]=input("请输入%s下新增的maxconn:"%add_input)
109 backend_name_add=add_input
110 backend_dict[backend_name_add]=add_dict
111
112 file_new = "%s_new"%file
113 with open(file,"r") as f_read, open(file_new,"a+")as f_write:
114 for line in f_read:
115 f_write.write(line)
116 f_write.write("\nbackend %s"%backend_name_add)
117 server_line_write = "\n\t\tserver {name} {ip} weight {weight} maxconn {maxconn}\n"
118 f_write.write(server_line_write.format(**add_dict))
119
120 os.system("mv %s %s_backup"%(file,file))
121 os.system("mv %s %s"%(file_new,file))
122 print("\nbackend %s" % backend_name_add)
123 print("name:%s IP:%s weight:%s maxconn:%s已添加成功" % (
124 add_dict["name"], add_dict["ip"], add_dict['weight'], add_dict['maxconn']))
125 break
126
127 #定义修改功能
128 def resive(resive_input):
129 resive_dict={}
130 if resive_input in backend_show_dict: #判断输入是否在
131 backend_resive = backend_show_dict[resive_input] #通过编号获取backend
132 resive_choise = input("是否需要修改该backend名称:%s;确认请按'y',按任意键继续;"%backend_resive)
133 if resive_choise == "y":
134 backend_resive_new = input("请输入修改后的backend的名称:")
135 backend_dict[backend_resive_new]=backend_dict.pop(backend_resive)
136 server_resive=input("是否需要修改%s下的server;确认请按‘y,按任意键继续’"%backend_resive_new)
137 if server_resive =="y":
138 server_resive_dict =server_show(backend_resive_new, backend_dict)
139 server_resive_num=input("请输入需要修改server的编号:")
140 resive_dict["name"]=input("请输入需要修改后server的名称:")
141 resive_dict["ip"]=input("请输入需要修改后ip:")
142 resive_dict["weight"]=input("请输入需要修改后weight:")
143 resive_dict["maxconn"]=input("请输入需要修改后maxconn:")
144 server_resive_dict[int(server_resive_num)]=resive_dict
145 server_resive_dict_backup ={}
146 server_resive_dict_backup[backend_resive_new]=server_resive_dict.values()
147 backup(file,backend_resive,server_resive_dict_backup,backend_resive_new)
148 else:
149 backup(file,backend_resive,backend_dict,backend_resive_new)
150 else:
151 server_resive_dict = server_show(backend_resive, backend_dict)
152 server_resive_num = input("请输入需要修改server的编号:")
153 resive_dict["name"] = input("请输入需要修改后server的名称:")
154 resive_dict["ip"] = input("请输入需要修改后ip:")
155 resive_dict["weight"] = input("请输入需要修改后weight:")
156 resive_dict["maxconn"] = input("请输入需要修改后maxconn:")
157 server_resive_dict[int(server_resive_num)] = resive_dict
158 server_resive_dict_backup = {}
159 server_resive_dict_backup[backend_resive] = server_resive_dict.values()
160 backup(file, backend_resive, server_resive_dict_backup)
161 else:
162 resive_input_return=input("输入的backend不存在,请重新输入:")
163 resive(resive_input_return)
164
165 #定义删除功能
166 def delete(delete_input):
167 if delete_input in backend_show_dict:
168 backend_delete = backend_show_dict[delete_input]
169 delete_choise = input("是否需要删除该backend:%s;确定请按'y',按任意键继续;"%backend_delete)
170 if delete_choise == "y":
171 del backend_dict[backend_delete]
172 backup(file,backend_delete,backend_dict)
173 else:
174 server_delete_dict= server_show(backend_delete,backend_dict)
175 server_delete_num = input("请输入需要删除的server的编号:")
176 while True:
177 if server_delete_num in server_delete_dict:
178 server_delete_dict.pop(server_delete_num)
179 server_delete_dict_backup={}
180 server_delete_dict_backup[backend_delete]=server_delete_dict.values()
181 backup(file,backend_delete,server_delete_dict_backup)
182 break
183 else:
184 server_delete_num = input("输入的编号不存在,请重新输入:")
185
186 #定义退出
187 def backend_exit():
188 flag_exit = True
189 b_input= input("退出请输入'b';")
190 while flag_exit:
191 if b_input == "b":
192 flag_exit = False
193 return flag_exit
194 else:
195 return backend_exit()
196
197 #定义文档备份
198 def backup(file,backend_name_action,backend_backup_dict,*backend_name_revise):
199 file_new="%s_new"%file
200 add_flag=False
201 with open(file,"r") as f_read,open(file_new,"w+")as f_write:
202 for line in f_read:
203 backend_name="backend %s"%backend_name_action
204 backend_name_revise="".join(tuple(backend_name_revise))
205 if line.strip() == backend_name:
206 if backend_name_action not in backend_backup_dict and backend_name_revise not in backend_backup_dict:
207 add_flag = True
208 pass
209 elif backend_name_revise in backend_backup_dict:
210 line_revise = "backend %s\n" % backend_name_revise
211 f_write.write(line_revise)
212 for add_dict in backend_backup_dict[backend_name_revise]:
213 server_line_write = '\t\tserver {name} {ip} weight {weight} maxconn {maxconn}\n'
214 f_write.write(server_line_write.format(**add_dict))
215 add_flag = True
216 else:
217 f_write.write(line)
218 for add_dict in backend_backup_dict[backend_name_action]:
219 server_line_write = '\t\tserver {name} {ip} weight {weight} maxconn {maxconn}\n'
220 f_write.write(server_line_write.format(**add_dict))
221 add_flag = True
222 elif line.strip().startswith("server") == True and add_flag == True:
223 pass
224 else:
225 f_write.write(line)
226 add_flag = False
227
228 os.system("mv %s %s_backup"%(file, file))
229 os.system("mv %s %s"%(file_new, file))
230
231
232
233
234
235
236
237 #主程序
238 flag = True
239 while flag:
240 flag_main = True
241 flag_action = True
242 file = "haproxy"
243 action_num = action_list()
244 (backend_list,backend_dict)=show_list(file)
245 backend_show_dict= backend_show(backend_list)
246
247
248 while flag_main:
249 if action_num == "1":
250 inquiry(input("请输入需要查询的backend编号或名称:"))
251 flag_main = backend_exit()
252 break
253
254 if action_num == "2":
255 add(input("请输入需要添加的现有backend编号或新backend名称:"),file)
256 flag_main = backend_exit()
257 break
258
259 if action_num == "3":
260 resive(input("请输入需要修改的backend编号或名称:"))
261 flag_main = backend_exit()
262 break
263
264 if action_num == "4":
265 delete(input("请输入需要删除的backend编号或名称:"))
266 flag_main = backend_exit()
267 break
268
269 if action_num == "5":
270 sys.exit()
271
272 elif action_num not in range(5):
273 print("你输入的有误,请重新输入")
274 flag_main = False