1 import os 2 def file_handler(backend,res=None,type='fetch'):# write the function to simplify the data 3 if type == 'fetch': 4 with open('proxy.conf','r') as read_f: 5 tag = False 6 ret = [] 7 7 for read_line in read_f: 8 8 if read_line.strip() = backend_data: 9 Tag = True 10 continue 11 if tag and read_line.startswith('backend'): 12 break 13 if tag: 14 print('\033[1;43m%s\033[0m' %read_line,end=' ') 15 ret.append(read_line) 16 return ret 17 if type == 'change': 18 with open('proxy.conf','r') as read_f,with open('proxy.conf_new','w') as write_f: 19 22 Tag =False 20 23 has_write == False 21 26 for read_line in read_f: 22 27 if read_line.strip() = backend_data: 23 28 Tag = True 24 continue 25 if tag and read_line.startswith('backend'): 26 Tag = False 27 if not tag: 28 write_f.write(read_line) 29 else: 30 if not has_write: 31 for record in res: 32 write_f.write(record) 33 has_write == True 34 35 def fetch(data): 36 2 print('\033[1;43mThis is fetch function\033[0m') 37 3 print('\033[1;43mThe data is\033[0m') 38 5 backend_data = 'backend %s' %data 39 6 return file_handler(backend_data) 40 9 41 10 def add(): 42 11 pass 43 12 def change(): 44 13 backend = data[0]['backend'] 45 14 backend_data = 'backend %s' % backend 46 15 old_server_record = '%sserver %s %s weight %s maxconn %s\n' %(' '*8,data[0]['record']['server'],data[0]['record']['server'],data[0]['record']['weight'],data[0]['record']['maxconn']) 47 16 new_server_record = '%sserver %s %s weight %s maxconn %s' %(''*8,data[1]['record']['server'],data[1]['record']['server'],data[1]['record']['weight'],data[1]['record']['maxconn']) 48 17 print('the data that user want changed is %s:' %old_server_record) 49 res = fetch(backend) 50 print('the data fron the res is %s:' %res) 51 18 if res == 0 or old_server_record not in res: 52 19 return 'There are not the content you find' 53 else: 54 20 index = res.index(old_server_record) 55 21 res[index] = new_server_record 56 24 res.insert(0,'%s\n' %backend_data) 57 25 return file_handler(backend_data,res=res,change) 58 59 os.rename('proxy.conf','proxy.conf.back') 60 os.rename('proxy.conf_new','proxy.conf') 61 os.remove('proxy.conf.back') 62 29 def delete(): 63 30 pass 64 31 if __name__ =='__main__':# judge the truth 65 32 msg = 66 33 ''' 67 34 1:查询 68 35 2:添加 69 36 3:修改 70 37 4:删除 71 38 5:退出 72 39 ''' 73 40 msg_dic = { 74 41 '1':fetch, 75 42 '2':add, 76 43 '3':change, 77 44 '4':delete 78 45 } 79 46 While True: 80 47 print(msg) 81 48 choice = input('Please input your choice:').strip() 82 49 if not choice:continue 83 50 if choice == '5':break 84 51 data = input('Please input your data:').strip() 85 52 if choice != 1: 86 53 data = eval(data) 87 54 msg_dic[choice](data) 88 55 #input the data: [{backend:www.oldboy1.org,record:server 2.2.2.4 2.2.2.4 weight 20 maxconn 3000},{backend:www.oldboy1.org,record:server 2.2.2.5 2.2.2.5 weight 20 maxconn 3000}]