對haproxy檔案進行增刪改查
阿新 • • 發佈:2018-12-09
1、檔案內容
global log 127.0.0.1 local2 daemon maxconn 256 log 127.0.0.1 local2 info defaults log global mode http timeout connect 5000ms timeout client 50000ms timeout server 50000ms option dontlognull listen stats :8888 stats enable stats uri/admin stats auth admin:1234 frontend oldboy.org bind 0.0.0.0:80 option httplog option httpclose option forwardfor log global acl www hdr_reg(host) -i www.oldboy.org use_backend www.oldboy.org if www backend www.oldboy.org server100.1.7.9 100.1.7.9 weight 20 maxconn 3000 server 100.1.7.19 100.1.7.19 weight 40 maxconn 4000 backend buy.oldboy.org server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000
2、程式碼實現
filename = 'text_file\haproxy' def fetch(backend): '''獲取檔案資料''' with open(filename, 'r') as f: result = [] flag = False for line in f: if line.strip().startswith('backend') and line.strip() == 'backend ' + backend: flag = True continue elif flag and line.startswith('backend'): break elif flag and line.strip(): result.append(line.strip()) return result #測試 ret = fetch("www.oldboy.org") print(ret) def add(backend,record): '''增加檔案資料''' record_list = fetch(backend) #先檢查backend是否存在 if not record_list: #backend不存在 with open(filename,'r') as old,open(r'text_file\new','w') as new: for line in old: new.write(line) new.write("\n\nbackend " + backend) new.write("\n" + " "*8 + record) else: #backend存在,判斷記錄是否存在 if record in record_list: #record存在 print("記錄已存在") else: #backend存在,record不存在 record_list.append(record) with open(filename,'r') as old,open(r'text_file\new2','w') as new2: flag = False for line in old: if line.strip().startswith('backend') and line.strip() == 'backend ' + backend: #找到backend www.oldboy.org flag = True new2.write(line)#把backend行加入新檔案 for new_record in record_list: #把record列表中的元素新增到新檔案 new2.write(" " * 8 + new_record + "\n") continue if flag and line.startswith('backend'): flag = False new2.write("\n" + line) continue if flag == False: new2.write(line) #測試 bk = "www.oldboy.org" rd = "server 34.1.7.25 100.1.7.44 weight 99 maxconn 67" add(bk,rd) bk = "test.oldboy.org" rd = "server 50.1.7.55 100.1.7.45 weight 99 maxconn 89" add(bk,rd) def delete(backend,record): '''刪除檔案資料''' #先判斷backend是否存在 record_list = fetch(backend) if not record_list: print("記錄不存在") else: with open(filename,'r') as f,open(r'text_file\new3','w') as new3: if record in record_list: for line in f: if line.strip() == record: continue else: new3.write(line) #測試 bk = "www.oldboy.org" rd = "server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000" delete(bk,rd)