首页 > 代码库 > Python蜕变-2017-4-23

Python蜕变-2017-4-23

  我的第一篇博客,这是试水练习。这次上的菜是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
View Code

 

<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 + "\n"
 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 + "\n"
 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("--------------------""\033[1;31;0m""HaProxy配置文件管理""\033[0m""-------------------------------")
 48     for i,n in enumerate(Info):
 49         show_list.append(n)
 50         print("\033[1;32;0m",i+1,n,"\033[0m")
 51     print("------------------------------------------------------------------------")
 52     order = input("请输入指令(A)新建、(D)删除、(M)修改、(C)查询、(Q)退出:")
 53     while order not in ("A","D","M","C","Q"):
 54         order = input("\033[1;31;0m""输入错误,请重新输入:""\033[0m")
 55     show_list = list(show_list)
 56     return order,show_list
 57 #----------------------------------------------Backend编号输入判断-------------------
 58 def Jude(choice,show_list):
 59     try:
 60         if eval(choice) not in range(len(show_list)+1):
 61             return True
 62         else:return False
 63     except:
 64         return True
 65 #----------------------------------------------Server编号判断-----------------------
 66 def JudeS(choiceS,a):
 67     try:
 68         if int(choiceS) in range(1,a+1) or int(choiceS) == 1:
 69             return False
 70         else:
 71             return True
 72     except:
 73         return True
 74 #----------------------------------------------新增信息判断--------------------------
 75 def JudeA(backend,weight,maxconn):
 76     try:
 77         if backend.startswith("www") and int(weight) in range(50) and int(maxconn) in range(5000):
 78             return False
 79     except:
 80         return True
 81 #----------------------------------------------查询---------------------------------
 82 def Check(show_list):
 83     choice = input("请选择backend:")
 84     while Jude(choice,show_list):
 85         choice = input("\033[1;31;0m""输入错误,请重新输入:""\033[0m")
 86     choice = int(choice)
 87     print("------------------------------",show_list[choice-1],"------------------------------")
 88     for a,b in enumerate(Info[show_list[choice-1]]):
 89             print("{} server:{}     weight:{}   maxconn:{}".format(a+1,b["server"],b["weight"],b["maxconn"]))
 90     print("----------------------------------------------------------------------------")
 91     select = input("请输入指令(Q)退出、(B)返回:")
 92     while select not in ("Q","B"):
 93         select = input("\033[1;31;0m""请输入正确指令:""\033[0m")
 94     if select == "Q":
 95         pass
 96     elif select == "B":
 97         main()
 98 #----------------------------------------------删除---------------------------------
 99 def Delete(show_list):
100     choice = input("删除Backend(B) or  Server(S)?:")
101     while(choice not in ("B","S")):
102         choice = input("\033[1;31;0m""请输入正确的指令:""\033[0m")
103     selection = input("请选择Backend编号:")
104     while Jude(selection,show_list):
105         selection = input("\033[1;31;0m""请输入正确的编号:""\033[0m")
106     selection = int(selection)
107     if choice =="B":
108         del Info[show_list[selection-1]]
109         Save_Info(Info)
110         print("\033[1;31;0m""删除成功!""\033[0m")
111         main()
112     elif choice == "S":
113         print("------------------------------",show_list[selection-1],"------------------------------")
114         for a,b in enumerate(Info[show_list[selection-1]]):
115             print("{} server:{}     weight:{}   maxconn:{}".format(a+1,b["server"],b["weight"],b["maxconn"]))
116         print("----------------------------------------------------------------------------")
117         choiceS = input("选择要删除的Server:")
118         while JudeS(choiceS,a):
119             choiceS = input("\033[1;31;0m""请输入正确的编号:""\033[0m")
120         choiceS = int(choiceS)
121         Info[show_list[selection-1]].pop(choiceS-1)
122         Save_Info(Info)
123         print("\033[1;31;0m""删除成功!""\033[0m")
124         main()
125 #----------------------------------------------增加---------------------------------
126 def Add():
127     print("————>请输入详细信息<————")
128     backend = input("Backend名称:")
129     server = input("Server名称:")
130     weight = input("权重(weight):")
131     maxconn = input("最大链接数(maxconn):")
132     while JudeA(backend,weight,maxconn):
133         print("\033[1;31;0m""输入信息错误,请重新输入!!!""\033[0m")
134         Add()
135     if backend not in Info:
136         Info[backend] = [{"server":server,"weight":weight,"maxconn":maxconn}]
137         print(">>>>>新建成功")
138     else:
139         flag = 1
140         for ser in Info[backend]:
141             if server == ser["server"]:
142                 flag = 0
143                 ser["weight"] = weight
144                 ser["maxconn"] = maxconn
145                 print(">>>>>backend及server信息已存在,""\033[1;31;0m""server信息已修改""\033[0m")
146         if flag:
147             Info[backend].append({"server":server,"weight":weight,"maxconn":maxconn})
148             print(">>>>>backend已存在,""\033[1;31;0m""server添加成功""\033[0m")
149     Save_Info(Info)
150     main()
151 #----------------------------------------------修改---------------------------------
152 def Modify(show_list):
153     selection = input("修改backend(B)  or  server(S)?>")
154     while (selection not in ("B","S")):
155         selection = input("\033[1;31;0m""请输入正确回答:""\033[0m")
156     choice = input("请输入要修改的backend编号:")
157     while Jude(choice,show_list):
158         choice = input("\033[1;31;0m""请输入正确编号:""\033[0m")
159     choice = int(choice)
160     if selection == "B":
161         backend = input("修改backend名称为:")
162         while not backend.startswith("www"):
163             backend = input("\033[1;31;0m""请输入合法的backend名称:""\033[0m")
164         temp = Info[show_list[choice-1]]
165         del Info[show_list[choice-1]]
166         Info[backend] = temp
167         Save_Info(Info)
168         print("\033[1;31;0m""修改backend成功""\033[0m")
169         main()
170     else:
171         print("------------------------------",show_list[choice-1],"------------------------------")
172         for a,b in enumerate(Info[show_list[choice-1]]):
173             print("{} server:{}     weight:{}   maxconn:{}".format(a+1,b["server"],b["weight"],b["maxconn"]))
174         print("----------------------------------------------------------------------------")
175         selection = input("修改哪个server?>")
176         while JudeS(selection,a):
177             selection = input("\033[1;31;0m""请输入正确的server编号:""\033[0m")
178         selection = int(selection)
179         sername = input("修改server为:")
180         Info[show_list[choice-1]][a-1]["server"] = sername
181         Save_Info(Info)
182         print("\033[1;31;0m""修改server成功""\033[0m")
183         main()
184 #----------------------------------------------指令处理------------------------------
185 def Deal_order(order,show_list):
186     if order =="Q":          #退出
187         pass
188     elif order =="A"  :      #新建
189         Add()
190     elif order == "D":       #删除
191         Delete(show_list)
192     elif order == "M":       #修改
193         Modify(show_list)
194     elif order == "C":
195         Check(show_list)
196     else:
197         order = input("\033[1;31;0m""输入错误,请重新输入:""\033[0m")
198         Deal_order(order,show_list)
199 #----------------------------------------------主函数--------------------------------
200 def main():
201     order,show_list = Show(Info)
202     Deal_order(order,show_list)
203 if __name__=="__main__":
204     Info = Deal_file()
205     main()
View Code

技术分享

<5>处理流程:

技术分享

 

<6>主要函数功能介绍:

   1.Deal_file():读取配置文件,并截取操作数据,通过String.startswith()找到截取位置获取数据,返回字典形式。

技术分享
 1 def Deal_file():
 2     s = ""
 3     Info = {}
 4     with open("配置文件.txt","r") as f:
 5         for i in f:
 6             if i.startswith("backend"):
 7                 backend = i.strip().split(" ")[1]
 8                 Info[backend] = []
 9             elif i.strip().startswith("server"):
10                 server = i.strip().split(" ")[1]
11                 weight = i.strip().split(" ")[3]
12                 maxconn = i.strip().split(" ")[5]
13                 Server = {"server":server,"weight":weight,"maxconn":maxconn}
14                 Info[backend].append(Server)
15             else:
16                 continue
17     return Info
View Code

  2.Save_Info():将操作后的数据与原始无关数据拼接保存,接收字典作为参数。

技术分享
 1 def Save_Info(Info):
 2     s = ""
 3     with open("配置文件.txt","r") as f:
 4         for i in f:
 5             if not i.startswith("backend"):
 6                 s = s + i
 7             else:
 8                 break
 9     s1 = ""
10     for backend in Info:
11         s2 = "backend " + backend
12         s1 = s1 + s2 + "\n"
13         for di in Info[backend]:
14             server = di["server"]
15             weight = di["weight"]
16             maxconn = di["maxconn"]
17             s3 = "      server {} weight {} maxconn {}".format(server,weight,maxconn)
18             s1 = s1 + s3 + "\n"
19     S = s + s1
20     with open("配置文件.txt","w+") as F:
21         F.write(S)
22     return(S)
View Code

  3.Show():将要操作的数据打印出来提示输入操作指令,白名单判断输入指令,进行判断,返回输入指令和打印列表。

  效果:

技术分享

技术分享
 1 def Show(Info):
 2     show_list = []
 3     print("--------------------""\033[1;31;0m""HaProxy配置文件管理""\033[0m""-------------------------------")
 4     for i,n in enumerate(Info):
 5         show_list.append(n)
 6         print("\033[1;32;0m",i+1,n,"\033[0m")
 7     print("------------------------------------------------------------------------")
 8     order = input("请输入指令(A)新建、(D)删除、(M)修改、(C)查询、(Q)退出:")
 9     while order not in ("A","D","M","C","Q"):
10         order = input("\033[1;31;0m""输入错误,请重新输入:""\033[0m")
11     show_list = list(show_list)
12     return order,show_list
View Code

  4.Jude()、JudeA()、JudeS()分别对输入的backend编号、server编号和新建的数据信息进行简单判断。

技术分享
 1 #----------------------------------------------Backend编号输入判断-------------------
 2 def Jude(choice,show_list):
 3     try:
 4         if eval(choice) not in range(len(show_list)+1):
 5             return True
 6         else:return False
 7     except:
 8         return True
 9 #----------------------------------------------Server编号判断-----------------------
10 def JudeS(choiceS,a):
11     try:
12         if int(choiceS) in range(1,a+1) or int(choiceS) == 1:
13             return False
14         else:
15             return True
16     except:
17         return True
18 #----------------------------------------------新增信息判断--------------------------
19 def JudeA(backend,weight,maxconn):
20     try:
21         if backend.startswith("www") and int(weight) in range(50) and int(maxconn) in range(5000):
22             return False
23     except:
24         return True
View Code

  5.Deal_order():接受来自Show()的返回值,对输入的指令进行分流给不同的函数处理。

技术分享
 1 def Deal_order(order,show_list):
 2     if order =="Q":          #退出
 3         pass
 4     elif order =="A"  :      #新建
 5         Add()
 6     elif order == "D":       #删除
 7         Delete(show_list)
 8     elif order == "M":       #修改
 9         Modify(show_list)
10     elif order == "C":
11         Check(show_list)
12     else:
13         order = input("\033[1;31;0m""输入错误,请重新输入:""\033[0m")
14         Deal_order(order,show_list)
View Code

  6.Check():查询,主要查看backend下的server信息。

  效果:

技术分享

技术分享
 1 #----------------------------------------------查询---------------------------------
 2 def Check(show_list):
 3     choice = input("请选择backend:")
 4     while Jude(choice,show_list):
 5         choice = input("\033[1;31;0m""输入错误,请重新输入:""\033[0m")
 6     choice = int(choice)
 7     print("------------------------------",show_list[choice-1],"------------------------------")
 8     for a,b in enumerate(Info[show_list[choice-1]]):
 9             print("{} server:{}     weight:{}   maxconn:{}".format(a+1,b["server"],b["weight"],b["maxconn"]))
10     print("----------------------------------------------------------------------------")
11     select = input("请输入指令(Q)退出、(B)返回:")
12     while select not in ("Q","B"):
13         select = input("\033[1;31;0m""请输入正确指令:""\033[0m")
14     if select == "Q":
15         pass
16     elif select == "B":
17         main()
View Code

  7.Add():新建,可以新建backend若已存在则在backend下新建server信息,若两种都存在则修改server信息。

技术分享

技术分享
 1 #----------------------------------------------增加---------------------------------
 2 def Add():
 3     print("————>请输入详细信息<————")
 4     backend = input("Backend名称:")
 5     server = input("Server名称:")
 6     weight = input("权重(weight):")
 7     maxconn = input("最大链接数(maxconn):")
 8     while JudeA(backend,weight,maxconn):
 9         print("\033[1;31;0m""输入信息错误,请重新输入!!!""\033[0m")
10         Add()
11     if backend not in Info:
12         Info[backend] = [{"server":server,"weight":weight,"maxconn":maxconn}]
13         print(">>>>>新建成功")
14     else:
15         flag = 1
16         for ser in Info[backend]:
17             if server == ser["server"]:
18                 flag = 0
19                 ser["weight"] = weight
20                 ser["maxconn"] = maxconn
21                 print(">>>>>backend及server信息已存在,""\033[1;31;0m""server信息已修改""\033[0m")
22         if flag:
23             Info[backend].append({"server":server,"weight":weight,"maxconn":maxconn})
24             print(">>>>>backend已存在,""\033[1;31;0m""server添加成功""\033[0m")
25     Save_Info(Info)
26     main()
View Code

  8.Delete():删除,可以删除backend或Server信息。

  效果:

技术分享

技术分享

 

技术分享
 1 #----------------------------------------------删除---------------------------------
 2 def Delete(show_list):
 3     choice = input("删除Backend(B) or  Server(S)?:")
 4     while(choice not in ("B","S")):
 5         choice = input("\033[1;31;0m""请输入正确的指令:""\033[0m")
 6     selection = input("请选择Backend编号:")
 7     while Jude(selection,show_list):
 8         selection = input("\033[1;31;0m""请输入正确的编号:""\033[0m")
 9     selection = int(selection)
10     if choice =="B":
11         del Info[show_list[selection-1]]
12         Save_Info(Info)
13         print("\033[1;31;0m""删除成功!""\033[0m")
14         main()
15     elif choice == "S":
16         print("------------------------------",show_list[selection-1],"------------------------------")
17         for a,b in enumerate(Info[show_list[selection-1]]):
18             print("{} server:{}     weight:{}   maxconn:{}".format(a+1,b["server"],b["weight"],b["maxconn"]))
19         print("----------------------------------------------------------------------------")
20         choiceS = input("选择要删除的Server:")
21         while JudeS(choiceS,a):
22             choiceS = input("\033[1;31;0m""请输入正确的编号:""\033[0m")
23         choiceS = int(choiceS)
24         Info[show_list[selection-1]].pop(choiceS-1)
25         Save_Info(Info)
26         print("\033[1;31;0m""删除成功!""\033[0m")
27         main()
View Code

  9.Modify():修改,修改backend或是Server信息。

  效果:

技术分享

技术分享

技术分享

 

技术分享
 1 def Modify(show_list):
 2     selection = input("修改backend(B)  or  server(S)?>")
 3     while (selection not in ("B","S")):
 4         selection = input("\033[1;31;0m""请输入正确回答:""\033[0m")
 5     choice = input("请输入要修改的backend编号:")
 6     while Jude(choice,show_list):
 7         choice = input("\033[1;31;0m""请输入正确编号:""\033[0m")
 8     choice = int(choice)
 9     if selection == "B":
10         backend = input("修改backend名称为:")
11         while not backend.startswith("www"):
12             backend = input("\033[1;31;0m""请输入合法的backend名称:""\033[0m")
13         temp = Info[show_list[choice-1]]
14         del Info[show_list[choice-1]]
15         Info[backend] = temp
16         Save_Info(Info)
17         print("\033[1;31;0m""修改backend成功""\033[0m")
18         main()
19     else:
20         print("------------------------------",show_list[choice-1],"------------------------------")
21         for a,b in enumerate(Info[show_list[choice-1]]):
22             print("{} server:{}     weight:{}   maxconn:{}".format(a+1,b["server"],b["weight"],b["maxconn"]))
23         print("----------------------------------------------------------------------------")
24         selection = input("修改哪个server?>")
25         while JudeS(selection,a):
26             selection = input("\033[1;31;0m""请输入正确的server编号:""\033[0m")
27         selection = int(selection)
28         sername = input("修改server为:")
29         Info[show_list[choice-1]][a-1]["server"] = sername
30         Save_Info(Info)
31         print("\033[1;31;0m""修改server成功""\033[0m")
32         main()
View Code

 

 

 

  

 

Python蜕变-2017-4-23