python函数部分练习--增删改查haproxy配置文件内容

import os

def file_handel(data,res=None,type="fetch"):
    if type == "fetch":
        server_ls = []
        with open('haproxy.conf', 'r', encoding='utf-8') as read_f:
            tag = False
            for readline in read_f:
                if readline.strip().startswith('backend'):
                    if readline.strip().split(' ')[-1] == data:
                        tag = True
                        continue
                if tag and readline.strip().startswith('backend'):
                    break
                if tag:
                    server_ls.append(readline)
        return server_ls
    elif type == "change":
        with open('haproxy.conf', 'r', encoding='utf-8') as read_f, \
                open('haproxy.conf_new', 'w', encoding='utf-8') as write_f:
            tag = False
            is_write = False
            for readline in read_f:
                if tag and readline.strip().startswith('backend'):
                    tag = False
                if not tag:
                    write_f.write(readline)
                else:
                    # write_f.write(res[index] if readline not in res else readline)
                    if not is_write:
                        write_f.writelines(res)
                        is_write = True

                if readline.strip().startswith('backend'):
                    if readline.strip().split(' ')[-1] == data[0]['backend']:
                        tag = True
        os.rename('haproxy.conf', 'haproxy.conf.bak')
        os.rename('haproxy.conf_new', 'haproxy.conf')
        os.remove('haproxy.conf.bak')
        return "OK"
    elif type == "add":
        with open('haproxy.conf', 'r', encoding='utf-8') as read_f ,\
            open('haproxy.conf_new','w',encoding='utf-8') as write_f:
            tag = False
            is_write = False
            for readline in read_f:
                if tag and readline.strip().startswith('backend'):
                    tag = False
                if not tag:
                    write_f.write(readline)
                else:
                    # write_f.write(res[index] if readline not in res else readline)
                    if not is_write:
                        write_f.writelines(res)
                        is_write = True

                if readline.strip().startswith('backend'):
                    if readline.strip().split(' ')[-1] == data['backend']:
                        tag = True
        os.rename('haproxy.conf', 'haproxy.conf.bak')
        os.rename('haproxy.conf_new', 'haproxy.conf')
        os.remove('haproxy.conf.bak')
        return "OK"
    elif type == 'delete':
        with open('haproxy.conf', 'r', encoding='utf-8') as read_f ,\
            open('haproxy.conf_new','w',encoding='utf-8') as write_f:
            tag = False
            is_write = False
            for readline in read_f:
                if tag and readline.strip().startswith('backend'):
                    tag = False
                if not tag:
                    write_f.write(readline)
                else:
                    # write_f.write(res[index] if readline not in res else readline)
                    if not is_write:
                        write_f.writelines(res)
                        is_write = True

                if readline.strip().startswith('backend'):
                    if readline.strip().split(' ')[-1] == data['backend']:
                        tag = True
        os.rename('haproxy.conf', 'haproxy.conf.bak')
        os.rename('haproxy.conf_new', 'haproxy.conf')
        os.remove('haproxy.conf.bak')
        return "OK"

def fetch(data):
    '''
    查询功能函数
    :param data:  传入需要查询的字段
    :return:
    '''
    server_ls = file_handel(data)
    return server_ls if server_ls else '没有匹配到backend相应的数据'

def add(data):
    res = fetch(data['backend'])
    new_server = '%sserver %s %s weight %s maxconn %s\n' % (' ' * 8,
                                                            data["record"]['server'],
                                                            data["record"]["server"],
                                                            data["record"]["weight"],
                                                            data["record"]["maxconn"])
    if  not isinstance(res,list):
        return "没有找到匹配的数据!"
    res.append(new_server)
    ret = file_handel(data, res=res, type="add")
    return ret

def change(data):
    '''
    修改数据函数
    :param data: 因为用户输入的是列表,所以在传入之前就应该做eval()操作
    :return:
    '''
    res = fetch(data[0]['backend'])
    old_server = '%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"])
    new_server = '%sserver %s %s weight %s maxconn %s\n' % (' ' * 8,
                                                            data[1]["record"]['server'],
                                                            data[1]["record"]["server"],
                                                            data[1]["record"]["weight"],
                                                            data[1]["record"]["maxconn"])
    if not res or old_server not in res:
        return "没有找到匹配的数据!"
    index = res.index(old_server)
    res[index] = new_server
    ret = file_handel(data,res=res,type="change")
    return  ret


def delete(data):
    res = fetch(data['backend'])
    new_server = '%sserver %s %s weight %s maxconn %s\n' % (' ' * 8,
                                                            data["record"]['server'],
                                                            data["record"]["server"],
                                                            data["record"]["weight"],
                                                            data["record"]["maxconn"])
    if not isinstance(res, list):
        return "没有找到匹配的数据!"
    res.remove(new_server)
    ret = file_handel(data, res=res, type="delete")
    return ret

if __name__ == '__main__':
    msg = '''
    1 :查询
    2 :添加
    3 :修改
    4 :删除
    q :退出
    '''

    msg_dic = {
        '1' : fetch ,
        '2' : add ,
        '3' : change ,
        '4' : delete
    }

    while True:
        choise = input(msg).strip()[0]
        if not choise: continue
        if choise == 'q':
            break

        data = input("请输入你的数据:").strip()
        if choise != '1':
            data = eval(data)
        res = msg_dic[choise](data)
        print(''.join(res))

# [{'backend':'www.oldboy1.org','record':{'server':'2.2.2.4','weight':20,'maxconn':3000}}, {'backend':'www.oldboy1.org','record':{'server':'10.10.2.4','weight':30,'maxconn':5000}}]
# [{'backend':'www.oldboy1.org','record':{'server':'10.10.2.4','weight':30,'maxconn':5000}}]

  

posted @ 2019-09-11 17:52  Mr-谢  阅读(149)  评论(0)    收藏  举报