s12-day03-work01 python修改haproxy配置文件(初级版本)

  1 #!/usr/local/env python3
  2 '''
  3 Author:@南非波波
  4 Blog:http://www.cnblogs.com/songqingbo/
  5 E-mail:qingbo.song@gmail.com
  6 '''
  7 import sys,time
  8 import module
  9 
 10 ha = './haproxy.conf'
 11 #选择功能
 12 def chooseView(choice):
 13     if choice == 1:  #获取配置文件所有内容
 14         print(module.getAllContent(ha))
 15         choice1 = input("请选择是否要继续(y/n):").strip()
 16         if choiceIf(choice1) == True:
 17             print("你选择的是继续,系统即将返回到系统主页!")
 18             time.sleep(1)
 19             chooseView(showView())
 20         if choiceIf(choice1) == False:
 21             print("你选择的是不继续操作,系统将退出!感谢你的使用!")
 22             time.sleep(1)
 23             sys.exit(0)
 24 
 25     if choice == 2:
 26         module.addLabelRecord(ha,getInputConnet())
 27     if choice == 3:
 28          module.delLabelRecord(ha,getInputConnet())
 29     if choice == 4:
 30         module.chgLabelRecord(ha)
 31     if choice == 'q':
 32         print("系统即将退出,感谢你的使用!")
 33         time.sleep(1)
 34         sys.exit(0)
 35 
 36 #判断用户输入,是否继续或返回
 37 def choiceIf(choice):
 38     if choice.isalpha():
 39         if choice == 'Y' or choice == 'y':
 40             return True
 41         elif choice == 'N' or choice == 'n':
 42             return False
 43         else:
 44             print("你的指令系统暂不支持!系统即将退出!")
 45             time.sleep(1)
 46             sys.exit(2)
 47     else:
 48         print("你输入的字符格式有误,系统将默认返回到主页!")
 49         time.sleep(1)
 50         chooseView(showView())
 51 
 52 def showView():
 53     print('''
 54     ****欢迎使用haproxy配置文件修改系统****
 55     	[1]获取配置文件信息		[2]增加模块配置
 56     	[3]删除模块配置    		[4]修改模块配置
 57     	[q]退出系统
 58     ************************************
 59     ''')
 60     while True:
 61         count = 0
 62         if count < 3:
 63             choice = input("	请选择相应指令:").strip()
 64             if choice.isdigit():
 65                 choice = int(choice)
 66                 if choice > 0 and choice < 5:
 67                     return choice
 68                 else:
 69                     count += 1
 70                     print("你的输入已超出指令范围!")
 71             elif choice == 'q':
 72                 return choice
 73             else:
 74                 count += 1
 75                 print("请输入正确的指令,指令为[1-4]的整型或q字符!")
 76         else:
 77             print("对不起,你的输入错误次数已达3次,系统即将退出,感谢你的使用!")
 78             time.sleep(1)
 79             sys.exit(1)
 80 
 81 #获取用户输入字典
 82 def getInputConnet():
 83     get_input_dict = {}
 84     count = 0
 85     while True:
 86         if count < 3:
 87             get_input_dict['label'] = input("请输入你需要增加记录内容的模块名称:").strip()
 88             get_input_dict['server'] = input("请输入server字段值:").strip()
 89             get_input_dict['weight'] = input("请输入weight字段值:").strip()
 90             get_input_dict['maxconn'] = input("请输入maxconn字段值:").strip()
 91             # if get_input_dict['label'].isalpha():
 92             if get_input_dict['label']:
 93                 getall_dict = module.getAllContentDict(ha) #获取配置文件总的字典
 94                 if get_input_dict['label'] in getall_dict.keys(): #用户输入的moudle在文件中存在,那就直接在原有的基础上增加记录值
 95                     return get_input_dict
 96                 # else: #label模块不存在,根据用户选择是否要创建
 97                 #     choice = input("你选择的模块不存在,是否要创建(y/n):").strip()
 98                 #     if choiceIf(choice) == True:
 99                 #         print("你选择的是继续,系统即将创建moudle %s!" % get_input_dict['label'])
100                 #         print('''即将创建的模块内容为:
101                 #         	%s
102                 #         			server %s weight %s maxconn %s

103                 #         ''' % (get_input_dict['label'],get_input_dict['server'],get_input_dict['weight'],get_input_dict['maxconn']))
104                 #         return get_input_dict
105                 #     if choiceIf(choice) == False:
106                 #         print("你选择的是不继续操作,系统将退出!感谢你的使用!")
107                 #         time.sleep(1)
108                 #         sys.exit(0)
109 
110             else:
111                 count += 1
112                 print("模块名称Label需要全为字母的字符!")
113         else:  #输错3次之后返回系统主页
114             print("你的输入错误次数已达3次,系统即将返回主页!")
115             time.sleep(1)
116             chooseView(showView())
117 
118 #main
119 if __name__ == "__main__":
120     ha = './haproxy.conf'
121     chooseView(showView())
index.py
  1 #!/usr/local/env python3
  2 '''
  3 Author:@南非波波
  4 Blog:http://www.cnblogs.com/songqingbo/
  5 E-mail:qingbo.song@gmail.com
  6 '''
  7 
  8 import json,os,shutil,time
  9 import index
 10 
 11 ha = "./haproxy.conf"
 12 
 13 #备份配置文件
 14 def haBak(ha):
 15     shutil.copyfile(ha,ha + '.bak')
 16 
 17 #获取文件行数
 18 def countnum(filename):
 19     files = open(filename)
 20     data = files.read()
 21     files.flush()
 22     files.close()
 23     return data.count('
')
 24 
 25 #获取文件所有内容
 26 def getAllContent(ha):
 27     with open(ha,'r+') as f:
 28         all_content = f.read() #获取文件所有内容
 29     return all_content
 30 
 31 #获取文件内容
 32 def getAllContentDict(ha):
 33     with open(ha,'r+') as f:
 34         all_content = f.read() #获取文件所有内容,类型为str
 35         all_content_dict = {} #初始化一个总的字典。将文件的所有内容都存档到该字典中
 36         record = [] #初始化一个record列表,该列表用来存储每个label下面的记录值
 37         for line in all_content.split('
'): #按照换行符进行每行内容遍历
 38             label_dict_temp = {} #初始化一个label的临时字典,该字典记录的是{label:record}
 39             if not line.startswith("        "): #判断每行内容是否为8个空格字符开头,这里取否,取的是label值
 40                 record = [] #每次获取label值都要对record列表进行初始化,这里修改的是全局变量
 41                 label_dict_temp[line] = record ##将record列表作为values值添加到label_dict_temp临时字典中
 42             else: #每行内容为8个空格字符开头,取得是label下面的record值
 43                 record.append(line.strip())  #将该行的值append到record列表中,每行记录值以元素的身份存在在record中
 44             all_content_dict.update(label_dict_temp) #将获取的{label:record}字典更新到总的字典中
 45     return all_content_dict #最后返回值为配置文件的label内容
 46 
 47 
 48 #增加模块记录值
 49 def addLabelRecord(ha,dict_input):
 50     with open(ha,'r') as all_content,open(ha+'.new','w+') as all_content_new:
 51         all_content_dict = getAllContentDict(ha)
 52         add_str = "        server %s %s weight %s maxconn %s
" % (dict_input['server'],dict_input['server'],dict_input['weight'],dict_input['maxconn'])
 53         if dict_input['label'] in all_content_dict.keys():
 54             flag = False
 55             for line in all_content.readlines():
 56                 all_content_new.write(line)
 57                 if line.strip('
') == dict_input['label']:
 58                     flag = True
 59                     continue
 60                 if flag:
 61                     all_content_new.write(add_str)
 62                     flag = False
 63         else:
 64             pass
 65 
 66     print("增加成功!")
 67     choice = input("请选择是否要更新到线上(y/n):").strip()
 68     if index.choiceIf(choice) == True:
 69         print("你选择的是更新到线上,系统即将把修改后的文件发布到线上并返回系统首页!")
 70         if os.path.exists(ha + '.bak'):
 71             os.remove(ha + '.bak')
 72         os.rename(ha,ha+'.bak')
 73         os.rename(ha+'.new',ha)
 74         time.sleep(1)
 75         index.chooseView(index.showView())
 76     if index.choiceIf(choice) == False:
 77         print("你选择的是放弃更新,系统即将返回系统首页!")
 78         if os.path.exist(ha + '.new'):
 79             os.remove(ha + '.new')
 80         index.chooseView(index.showView())
 81 
 82 def delLabelRecord(ha,dict_input):
 83     with open(ha,'r') as all_content,open(ha+'.new','w+') as all_content_new:
 84         all_content_dict = getAllContentDict(ha)
 85         del_str = "        server %s %s weight %s maxconn %s
" % (dict_input['server'],dict_input['server'],dict_input['weight'],dict_input['maxconn'])
 86         if dict_input['label'] in all_content_dict.keys():
 87             flag = False
 88             for line in all_content.readlines():
 89                 if line.strip('
') == dict_input['label']:
 90                     flag = True
 91                     all_content_new.write(line)
 92                     continue
 93                 if flag == True and line == del_str:
 94                     flag = False
 95                     continue
 96                 all_content_new.write(line)
 97         else:
 98             pass
 99     print("删除成功!")
100     choice = input("请选择是否要更新到线上(y/n):").strip()
101     if index.choiceIf(choice) == True:
102         print("你选择的是更新到线上,系统即将把修改后的文件发布到线上并返回系统首页!")
103         if os.path.exists(ha + '.bak'):
104             os.remove(ha + '.bak')
105         os.rename(ha,ha+'.bak')
106         os.rename(ha+'.new',ha)
107         time.sleep(1)
108         index.chooseView(index.showView())
109     if index.choiceIf(choice) == False:
110         print("你选择的是放弃更新,系统即将返回系统首页!")
111         if os.path.exists(ha + '.new'):
112             os.remove(ha + '.new')
113         index.chooseView(index.showView())
114 
115 def chgLabelRecord(ha):
116     #获取用户修改label记录值
117     print("下面请按照提示输入你要修改的记录值!")
118     dict_input1 = index.getInputConnet()
119     print("下面请按照提示输入你要修改后的记录值!")
120     dict_input2 = index.getInputConnet()
121     with open(ha,'r') as all_content,open(ha+'.new','w+') as all_content_new:
122         all_content_dict = getAllContentDict(ha)
123         old_str = "        server %s %s weight %s maxconn %s
" % (dict_input1['server'],dict_input1['server'],dict_input1['weight'],dict_input1['maxconn'])
124         new_str = "        server %s %s weight %s maxconn %s
" % (dict_input2['server'],dict_input2['server'],dict_input2['weight'],dict_input2['maxconn'])
125         print(new_str)
126         if dict_input1['label'] in all_content_dict.keys():
127             flag = False
128             for line in all_content.readlines():
129                 if line.strip('
') == dict_input1['label']:
130                     flag = True
131                     all_content_new.write(line)
132                     continue
133                 if flag == True and line == old_str:
134                     all_content_new.write(new_str)
135                     flag = False
136                     continue
137                 all_content_new.write(line)
138         else:
139             pass
140     print("修改成功!")
141     choice = input("请选择是否要更新到线上(y/n):").strip()
142     if index.choiceIf(choice) == True:
143         print("你选择的是更新到线上,系统即将把修改后的文件发布到线上并返回系统首页!")
144         if os.path.exists(ha + '.bak'):
145             os.remove(ha + '.bak')
146         os.rename(ha,ha+'.bak')
147         os.rename(ha+'.new',ha)
148         time.sleep(1)
149         index.chooseView(index.showView())
150     if index.choiceIf(choice) == False:
151         print("你选择的是放弃更新,系统即将返回系统首页!")
152         if os.path.exists(ha + '.new'):
153             os.remove(ha + '.new')
154         index.chooseView(index.showView())
module.py

github代码更新地址:https://github.com/swht/projects/tree/master/day03/

原文地址:https://www.cnblogs.com/songqingbo/p/5149909.html