1. 程式人生 > >day2 文件實例

day2 文件實例

def log haproxy配置 內容 空格 dex start view 轉換

程序1: 實現簡單的shell sed替換功能

技術分享圖片
old = input(你要修改原來的內容:)
new = input(輸入修改後的內容:)
with open(old,r,encoding=utf-8) as f,    open(new,a,encoding=utf-8) as f1:#old舊的文件,new新的文件
    for line in f:
        if old in line:
            line = line.replace(old,new)
        f1.write(line)#將替換後的內容寫入新文件
View Code

程序2:修改haproxy配置文件

配置文件:

技術分享圖片
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
        server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
View Code

技術分享圖片
# Author Cathy
current_index = -1
dict_all = {}
old_content = []
#將backend下的內容找到,並且變成字典的形式
with open("haproxy","r",encoding=utf-8) as f:
    for index,line in enumerate(f):

        if line.startswith("backend"):#判斷是否是以backend為開頭的
            current_index = index + 1#將下標置為0
            nod = line.strip().split()[1]#
將‘backend www.oldboy.org‘轉換成列表,並且刪除前後的空格,以中間空格分成列表,nod為www.oldboy.org dict_all["backend"] = nod#生成一個{‘bakend‘: ‘www.oldboy.org‘}字典 elif index == current_index: dict_all["record"] = {} dict_all["record"]["server"] = line.strip().split()[1],line.strip().split()[2] dict_all["record"]["weight"] = line.strip().split()[4] dict_all["record"]["maxconn"] = line.strip().split()[6] else: old_content.append(line.strip()) print(以下功能可使用:\n1.查詢\n2.修改\n3.刪除\n4.退出\n) flag = True while flag: option = int(input(請輸入功能編號:)) #查詢 if option == 1: backend_1 = input(請輸入你要查詢baclend下的節點:) for line in dict_all: if backend_1 in dict_all[line]: print(dict_all) else: continue #修改 elif option == 2: backend_2 = input(請輸入你要修改baclend下的節點:) dict_all["backend"]= backend_2 dict_all["record"] = {} dict_all["record"]["server"] = input(輸入server:) dict_all["record"]["weight"] = input(輸入weight:) dict_all["record"]["maxconn"] = input(輸入maxconn:) #刪除 elif option ==3: backend_3 = input(請輸入你要刪除baclend下的節點:) if backend_3 == dict_all[backend]: dict_all= {} print("刪除成功!") else: print("沒有這個節點,重新輸入!") elif option == 4: for i in old_content: f = open("haproxy_new", "a") f.write("%s\n"%i) if dict_all != {}: open("haproxy_new", "a").write("backend %s\n\tserver%s weight %s maxconn %s\n\n" % ( dict_all["backend"], dict_all["record"]["server"], dict_all["record"]["weight"], dict_all["record"]["maxconn"])) f.close() flag = False else: pass
View Code

day2 文件實例