import os def futch(data): # print('这里是查询功能') # print('要查询的数据是:',data) backend_data = 'backend %s' % data with open('haproxy.conf', 'r') as read_f: tag = False result = [] for read_line in read_f: if read_line.strip() == backend_data: tag = True continue if tag and read_line.startswith('backend'): # tag=False break if tag: # print(read_line,end='') result.append(read_line) return result def add(): print('这里是添加功能') def change(data): # print('这里是修改功能') # print('想要修改的是:',date) backend = data[0]['backend'] # backend=www.oldboy1.org backend_data = 'backend %s' % backend # print(backend) old_server_record = '%sserver %s weight %s maxconn %s ' % (' ' * 8, data[0]['record']['server'], data[0]['record']['weight'], data[0]['record']['maxconn'] ) new_server_record = '%sserver %s weight %s maxconn %s ' % (' ' * 8, data[1]['record']['server'], data[1]['record']['weight'], data[1]['record']['maxconn'] ) # print('用户想要修改的数据是:',old_server_record) # print('用户想要改成的数据是:', new_server_record) result = futch(backend) # print(result) if not result or old_server_record not in result: print('未找到想要修改的数据') index = result.index(old_server_record) result[index] = new_server_record # print(result) result.insert(0, '%s ' % backend_data) # print(result) with open('haproxy.conf', 'r') as read_f, open('haproxy.conf_new', 'w') as write_f: tag = False write_tag = False for read_line in read_f: if read_line.strip() == backend_data: tag = True continue if tag and read_line.startswith('backend'): tag = False if not tag: write_f.write(read_line) else: if not write_tag: for record in result: write_f.write(record) write_tag = True def delete(): print('这里是删除功能') if __name__ == '__main__': masage = ''' 1:查询 2:添加 3:修改 4:删除 5:退出 ''' masage_dic = { '1': futch, '2': add, '3': change, '4': delete } while 'True': print(masage) choice = input('请输入你的选项:').strip() if not choice: continue if choice == '5': break data = input('请输入数据:').strip() if choice != '1': data = eval(data) res = masage_dic[choice](data) print(res) # [{'backend':'www.oldboy1.org','record':{'server':'2.2.2.5 2.2.2.5','weight':'30','maxconn':'4000'}},{'backend':'www.oldboy1.org','record':{'server':'2.2.2.4 2.2.2.4','weight':'30','maxconn':'4000'}}]