对haproxy文件后端信息进行增删查(python3.x)
程序员文章站
2022-06-10 10:37:37
1,程序要求 1 1、查 2 输入:www.oldboy.org 3 获取当前backend下的所有记录 4 5 2、新建 6 输入: 7 arg = { 8 'backend': 'www.oldboy.org', 9 'record':{ 10 'server': '100.1.7.9', 11 ......
1,程序要求
1 1、查 2 输入:www.oldboy.org 3 获取当前backend下的所有记录 4 5 2、新建 6 输入: 7 arg = { 8 'backend': 'www.oldboy.org', 9 'record':{ 10 'server': '100.1.7.9', 11 'weight': 20, 12 'maxconn': 30 13 } 14 } 15 16 3、删除 17 输入: 18 arg = { 19 'backend': 'www.oldboy.org', 20 'record':{ 21 'server': '100.1.7.9', 22 'weight': 20, 23 'maxconn': 30 24 } 25 } 26 27 复制代码
1 global 2 log 127.0.0.1 local2 3 daemon 4 maxconn 256 5 log 127.0.0.1 local2 info 6 defaults 7 log global 8 mode http 9 timeout connect 5000ms 10 timeout client 50000ms 11 timeout server 50000ms 12 option dontlognull 13 14 listen stats :8888 15 stats enable 16 stats uri /admin 17 stats auth admin:1234 18 19 frontend oldboy.org 20 bind 0.0.0.0:80 21 option httplog 22 option httpclose 23 option forwardfor 24 log global 25 acl www hdr_reg(host) -i www.oldboy.org 26 use_backend www.oldboy.org if www 27 28 backend www.oldboy.org 29 server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
输入以上信息可以达到需要的效果
1 def find_web_info(x): 2 if choice_num==1: 3 with open("haproxy_file",'r') as f: 4 for line in f: 5 if line.startswith("backend %s" %x): 6 for i in range(10000): 7 read=f.readline() 8 if read.startswith('backend'): 9 break 10 elif read.strip()=='': 11 pass 12 else: 13 print(read) 14 else: 15 pass
1 def create_web_info(x): 2 key_list=[] 3 key1_list=[] 4 with open("haproxy_file",'a') as f: 5 f.write('bakend'+' '+x["bakend"]+'\n') 6 web_info_dic=x['record'] 7 f.write('\t\t'+'server'+' '+web_info_dic['server']+' '+'weight'+' '\ 8 +str(web_info_dic['weight'])+' '+'maxconn'+' '+str(web_info_dic['maxconn'])+'\n') 9 print("写入后端信息成功")
1 def delete_web_info(x): 2 find_line='' 3 backend_name='bakend'+' '+x["bakend"] 4 backend_name=backend_name.strip() 5 web_info_dic=x['record'] 6 back_info='server'+' '+web_info_dic['server']+' '+'weight'+' '\ 7 +str(web_info_dic['weight'])+' '+'maxconn'+' '+str(web_info_dic['maxconn']) 8 back_info=back_info.strip() 9 with open("haproxy_file",'r') as f: 10 for line in f: 11 if backend_name in line: 12 line=line.replace(line,'') 13 elif back_info in line: 14 line=line.replace(line,'') 15 else: 16 pass 17 find_line+=line 18 with open("haproxy_file",'w') as f1: 19 f1.write(find_line ) 20 print("后端信息删除完成")
1 while True: 2 print(''' 3 welecome to haproxy file 4 1.find_web_info 5 2.create_web_info 6 3.delete_web_ifo 7 ''') 8 choice_num=int(input("输入你对haproxy文件的操作选择:")) 9 if choice_num ==1: 10 find_name=input("输入需要查找的域名:") 11 find_web_info(find_name ) 12 elif choice_num ==2: 13 create_info=input("输入你插入的后端信息:") 14 create_info =eval(create_info ) 15 create_web_info(create_info) 16 elif choice_num ==3: 17 delete_info=input("输入你删除的信息:") 18 delete_info =eval(delete_info ) 19 delete_web_info(delete_info ) 20 else: 21 print("输入有误,请再输入一次")