我的第一篇博客,这是试水练习。这次上的菜是Haporxy配置文件操作。
<1> 上需求:
具体配置文件如下:
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 weight 20 maxconn 3000
<2>分析需求:
1.将配置文件中的主要信息也就是“backend”后的数据展示出来。
2.能够对数据进行增删改查的操作。
3.每次操作后进行备份。
<3>功能分析:
1.读取配置文件并截取有用数据打印。
2.具备增删改查功能,在此有用户输入,所以有必要进行判断,防止错误输入导致程序崩溃。
3.将操作后的数据与原始的无关数据进行拼接写入配置文件
<4>完整代码:
1 #--------------------------Haporxy配置文件操作-------------------------------------- 2 #py3.4 by:羽凡 2017-4-23 3 #----------------------------------------------读取文件处理数据(返回字典Info{})------- 4 def Deal_file(): 5 s = "" 6 Info = {} 7 with open("配置文件.txt","r") as f: 8 for i in f: 9 if i.startswith("backend"): 10 backend = i.strip().split(" ")[1] 11 Info[backend] = [] 12 elif i.strip().startswith("server"): 13 server = i.strip().split(" ")[1] 14 weight = i.strip().split(" ")[3] 15 maxconn = i.strip().split(" ")[5] 16 Server = {"server":server,"weight":weight,"maxconn":maxconn} 17 Info[backend].append(Server) 18 else: 19 continue 20 return Info 21 #----------------------------------------------信息保存----------------------------- 22 def Save_Info(Info): 23 s = "" 24 with open("配置文件.txt","r") as f: 25 for i in f: 26 if not i.startswith("backend"): 27 s = s + i 28 else: 29 break 30 s1 = "" 31 for backend in Info: 32 s2 = "backend " + backend 33 s1 = s1 + s2 + " " 34 for di in Info[backend]: 35 server = di["server"] 36 weight = di["weight"] 37 maxconn = di["maxconn"] 38 s3 = " server {} weight {} maxconn {}".format(server,weight,maxconn) 39 s1 = s1 + s3 + " " 40 S = s + s1 41 with open("配置文件.txt","w+") as F: 42 F.write(S) 43 return(S) 44 #----------------------------------------------展示信息,返回指令--------------------- 45 def Show(Info): 46 show_list = [] 47 print("--------------------""