修改haproxy配置文件
1 def search(): #查找域名函数 2 """ 3 1.readlines将内容变成一个列表 4 2.找到域名对应的索引 5 3.域名接下来几行是具体的服务器信息,利用上面索引循环加1遍历 6 """ 7 url = 'www.oldboy.net' 8 url_title = 'backend %s\n' % url 9 with open('haproxy.txt','r') as f: 10 f_read = f.readlines() 11 if url_title in f_read: 12 index = f_read.index(url_title) 13 print(f_read[index]) 14 index = index + 1 15 while index < len(f_read): 16 # print(len(f_read)) 17 if 'weight' in f_read[index] : 18 print(f_read[index]) 19 index+=1 20 else: 21 break 22 else: 23 exit('没有此域名') 24 25 def modifeild(): #删除 26 """ 27 1.利用上面查找的方法,先把域名对应条目索引取出放在一个列表中 28 2.再将老文件内容逐行写入新文件,当索引在上面列表时就忽略不写入,(然后把旧文件删除,新文件改成旧文件名,这部分没写) 29 """ 30 url = 'www.oldboy.ne' 31 url_title = 'backend %s\n' % url 32 index_list = [] 33 with open('haproxy.txt', 'r') as f,open('haproxynew.txt', 'w+') as fnew: 34 f_read = iter(f.readlines()) 35 if url_title in f_read: 36 index = f_read.index(url_title) 37 print(f_read[index]) 38 index_list.append(index) 39 print(index_list) 40 index = index + 1 41 while index < len(f_read): 42 # print(len(f_read)) 43 if 'weight' in f_read[index]: 44 index_list.append(index) 45 print(f_read[index]) 46 print(index_list) 47 index += 1 48 else: 49 for i,line in enumerate(f_read): 50 if i in index_list: 51 pass 52 else: 53 fnew.write(line) 54 else: 55 exit('没有此域名') 56 57 def add(): #新增 58 '''" 59 首次新增时,域名和服务器信息一起添加,再次添加时,只添加服务器信息 60 """ 61 url = 'www.baidu.com' 62 url_title = 'backend www.baidu.com\n' 63 server = '1.1.1.3' 64 weight = '30' 65 maxconn = '3000' 66 with open('haproxy.txt', 'r+') as f: 67 f_read = f.readlines() 68 print(f_read) 69 if url_title in f_read: 70 content = "\t\tserver {} {} weight {} maxconn {}\n" \ 71 .format(server, server, weight, maxconn) 72 print(content) 73 f.write(content) 74 else: 75 print(url_title) 76 f.write('\n') 77 f.write(url_title) 78 content = "\t\tserver {} {} weight {} maxconn {}\n" \ 79 .format(server, server, weight, maxconn) 80 print(content) 81 f.write(content)