python 基础 4.1 open 打开文件练习:修改haproxy配置文件

 

1、如何在线上环境优雅的修改配置文件?

配置文件名称ini

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
原配置文件
1、查
    输入:www.oldboy.org
    获取当前backend下的所有记录

2、新建
    输入:
        arg = {
            'bakend': 'www.oldboy.org',
            'record':{
                'server': '100.1.7.9',
                'weight': 20,
                'maxconn': 30
            }
        }

3、删除
    输入:
        arg = {
            'bakend': 'www.oldboy.org',
            'record':{
                'server': '100.1.7.9',
                'weight': 20,
                'maxconn': 30
            }
        }

 

我的代码:  配置文件代码ini

#!/usr/bin/env python 
#_*_coding:utf-8
__author__ = 'liujianzuo'


arg = {
    'bakend': '',
    'record': {
        'server': '',
        'weight': "",
        'maxconn': ""
    }
}
# arg = {'bakend': 'www.baidu.com', 'record': {'maxconn': '1', 'weight': '32232', 'server': '11.77.22.2'}}

def ming():
    l2 = []
    name = input("输入添加条目的域名:").strip()
    IP = input("输入添加条目的IP:").strip()
    weight = input("输入添加条目的weight:").strip()
    maxconn = input("输入添加条目的maxconn:").strip()
    l2.append(name)
    l2.append(IP)
    l2.append(weight)
    l2.append(maxconn)
    arg["bakend"] = name
    arg["record"]["server"] = IP
    arg["record"]["weight"] = weight
    arg["record"]["maxconn"] = maxconn
    return  l2

def file_hand(name):
    flag = 0
    li = []
    with open("ini",'r',encoding="utf-8") as f:
        for l in f:
            if l.strip() == "backend %s" % name:
                flag = 1
                continue
            if flag and  l.strip().startswith("backend"):
                flag = 0
            if flag :
                li.append(l.strip())
    return li

def add_file(add_content):
    l1 = []
    name = arg["bakend"]
    ret  = file_hand(name)
    x = arg["record"]
    new_line = "server" + " " + str(x["server"]) + " " + str(x["server"]) + " " + "weight" + " " + str(x["weight"]) + " " + "maxconn" + " " + str(x["maxconn"])
    if len(ret) == 0:
        with open("ini", "a+", encoding="utf-8") as f:
            f.write("\nbackend %s"%name)
            f.write("\n\t\t%s"%new_line)
    else:
        n_flag = 0
        with open("ini","r",encoding='utf-8') as f1:
            for m in f1:
                if len(m.strip()) == 0:
                    continue
                l1.append(m)
        with  open("ini",'w',encoding="utf-8") as f2:
            for line in l1:
                if ( n_flag == 1 or n_flag ==2 or n_flag ==3) and line.strip().startswith("backend"):
                    n_flag = 3
                    f2.write("\n%s"%line.strip())
                elif not n_flag and line.strip() != "backend %s"%name:
                    if len(line) == 0:
                        continue
                    else:
                        f2.write(line)
                elif n_flag and  line.strip() != "backend %s"%name:
                    if new_line not in ret :
                        n_flag =2
                        ret.append(new_line)
                        for kli in ret:
                            f2.write("\n\t\t%s"%kli)
                    else:
                        if n_flag == 2:
                            continue
                        elif n_flag == 3:
                            f2.write("\n\t\t%s"%line.strip())
                elif line.strip() == "backend %s"%name:
                    n_flag = 1
                    f2.write(line.strip())
                    continue
    return new_line

def del_conf(add_content):
    l1 = []
    name = arg["bakend"]
    ret  = file_hand(name)
    x = arg["record"]
    new_line = "server" + " " + str(x["server"]) + " " + str(x["server"]) + " " + "weight" + " " + str(x["weight"]) + " " + "maxconn" + " " + str(x["maxconn"])
    if len(ret) == 0:
        with open("ini", "a+", encoding="utf-8") as f:
            f.write("\nbackend %s"%name)
            f.write("\n\t\t%s"%new_line)
    else:
        n_flag = 0
        with open("ini","r",encoding='utf-8') as f1:
            for m in f1:
                if len(m.strip())==0:
                    continue
                l1.append(m)
        with  open("ini",'w',encoding="utf-8") as f2:
            for line in l1:
                if ( n_flag == 1 or n_flag ==2 or n_flag ==3) and line.strip().startswith("backend"):
                    n_flag = 3
                    f2.write("\n%s"%line.strip())
                elif not n_flag and line.strip() != "backend %s"%name:
                    f2.write(line)
                elif n_flag and  line.strip() != "backend %s"%name:
                    if new_line in ret:
                        n_flag =2
                        ret.remove(new_line)
                        for kli in ret:
                            f2.write("\n\t\t%s"%kli)
                    elif new_line == line:
                        continue
                    else:
                        if n_flag == 2:
                            continue
                        elif n_flag == 3:
                            f2.write("\n\t\t%s"%line.strip())
                elif line.strip() == "backend %s"%name:
                    n_flag = 1
                    continue
    return new_line

def main():
    print("""\033[33;1m\
    =============
    |1  获取数据|
    |2  添加数据|
    |3  删除数据|
    =============\033[0m\
    """)

    while True:
        chose = input("pls input your chose,q|Q for leave:").strip()
        if len(chose) == 0:
            continue
        elif chose.lower() == "q":
            exit("bye bye")
        elif not chose.isdigit():
            continue
        elif int(chose) == 1:
            name = input("输入查询的域名:").strip()
            ret = file_hand(name)
            if len(ret) == 0:
                print("你要查询的域名不存在")
            else:
                for x in ret:
                    print(x)
            main()
        elif int(chose) == 2:
            ret = ming()
            name = ret[0]
            ret = add_file(name)
            print("添加的数据如下:",ret)
            main()
        elif int(chose) == 3:
            ret = ming()
            name = ret[0]
            ret = del_conf(name)
            print("删除的数据如下:",ret)
            main()
        else:
            print("序号不存在!")
            main()
if __name__ == "__main__":
    main()

    # name = "www.baidu.com"
    # name = arg["bakend"]

    # ret = file_hand(name)
    # print(ret)
    # add_file(name)
    # del_conf(name)

  

 

posted @ 2016-05-29 17:08  众里寻,阑珊处  阅读(304)  评论(0编辑  收藏  举报
返回顶部