博客园 首页 私信博主 显示目录 隐藏目录 管理 动画

day 3 修改haproxy.cfg 作业

                           修改haproxy配置文件 

转载自:http://blog.csdn.net/ygqygq2/article/details/53343847

心得: 最开始的时候看对方的代码一脸蒙蔽。后面一行行的代码去做类似的操作,慢慢地想通了,

程序中出现了一个 global 的内部宣告全局的变量。这个是我觉得不好的地方。还有一个writer 函数可以和add 合并在一起,

最后那个写的确实让我想了很久。不过已经过去了,过程很美妙,没有编程基础的伙伴们,建议多抄一些代码。先抄一遍代码,

后面再去理解,这样记忆更深刻。 

查
    输入: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
            }
        }

作业需求 
HAproxy配置文件操作 
1. 根据用户输入,输出对应的backend下的server信息 
2. 可添加backend 和sever信息 
3. 可修改backend 和sever信息 
4. 可删除backend 和sever信息 
5. 操作配置文件前进行备份 
6. 添加server信息时,如果ip已经存在则修改;如果backend不存在则创建;若信息与已有信息重复则不操作

    • [x] 博客
    • [x] 查询backend下的server信息
    • [x] 添加backend和server信息
    • [ ] 修改backend 和sever信息
    • [x] 删除backend和server信息

 

 

 

思维导图

 

 

大佬写的

#!/usr/bin/env python
# _*_coding:utf-8_*_
'''
 * Created on 2016/11/7 21:24.
 * @author: Chinge_Yang.
'''

import shutil
import json


def list_function():
    print("Please choice the ID of a action.".center(50, "#"))
    print("[1] 查询 haproxy.cfg backend 信息.")
    print("[2] 添加 haproxy.cfg backend 信息")
    print("[3] 删除 haproxy.cfg backend 信息")
    print("End".center(50, "#"))


def fetch(backend):
    # 取出backend相关server信息
    result = []  # 定义结果列表
    with open("haproxy.cfg", "r", encoding="utf-8") as f:  # 循环读取文件
        flag = False  # 标记为假
        for line in f:
            # 以backend开头
            line = line.strip()
            if line.startswith("backend") and line == "backend " + backend:
                flag = True  # 读取到backend开头的信息,标记为真
                continue
            # 下一个backend开头
            if flag and line.strip().startswith("backend"):
                flag = False
                break
            # server信息添加到result列表
            if flag and line.strip():
                result.append(line.strip())
    return result


def writer(backend, record_list): ##3条
    with open("haproxy.cfg", "r") as old, open("new.cfg", "w") as new:
        flag = False
        for line in old:
            if line.strip().startswith('backend') and line.strip() == "backend " + backend:
                flag = True
                new.write(line)
                for new_line in record_list:
                    new.write(" " * 4 + new_line + "\n")
                continue  # 跳到下一次循环,避免下一个backend写二次

            if flag and line.strip().startswith("backend"):  # 下一个backend
                flag = False
                new.write(line)
                continue  # 退出此循环,避免server信息二次写入
            if line.strip() and not flag:
                new.write(line)


def add(backend, record):
    global change_flag
    record_list = fetch(backend)  # 查找是否存在记录 这个是 fetch 返回值
    print(record_list)
    if not record_list:  # backend不存在, record不存在
        with open('haproxy.cfg', 'r') as old, open('new.cfg', 'w') as new:
            for line in old:
                new.write(line)
            # 添加新记录
            new.write("\nbackend " + backend + "\n")
            new.write(" " * 4 + record + "\n")
        print("\033[32;1mAdd done\033[0m")
        change_flag = True
    else:  # backend存在,record存在
        if record in record_list:
            print("\033[31;1mRecord already in it,Nothing to do!\033[0m")
            change_flag = False
        else:  # backend存在,record不存在
            record_list.append(record)
            writer(backend, record_list)
            print(record_list)
            print("\033[32;1mAdd done\033[0m")
            change_flag = True


def delete(backend, record):
    global change_flag
    record_list = fetch(backend)  # 查找是否存在记录
    if not record_list:  # backend不存在, record不存在
        print("Not match the backend,no need delete!".center(50, "#"))
        change_flag = False
    else:  # backend存在,record存在
        if record in record_list:
            record_list.remove(record)  # 移除元素
            writer(backend, record_list)  # 写入
            print("\033[31;1mDelete done\033[0m")
            change_flag = True
        else:  # backend存在,record不存在
            print("Only match backend,no need delete!".center(50, "#"))
            change_flag = False
    return change_flag


def output(servers):
    # 输出指定backend的server信息
    print("Match the server info:".center(50, "#"))
    for server in servers:
        print("\033[32;1m%s\033[0m" % server)
    print("#".center(50, "#"))


def input_json():
    # 判断输入,要求为json格式
    continue_flag = False
    while continue_flag is not True:
        backend_record = input("Input backend info(json):").strip()
        try:
            backend_record_dict = json.loads(backend_record)
        except Exception as e:
            print("\033[31;1mInput not a json data type!\033[0m")
            continue
        continue_flag = True
    return backend_record_dict


def operate(action):
    global change_flag
    if action == "fetch":
        backend_info = input("Input backend info:").strip()
        result = fetch(backend_info)  # 取出backend信息
        if result:
            output(result)  # 输出获取到的server信息
        else:
            print("\033[31;1mNot a match is found!\033[0m")
    elif action is None:
        print("\033[31;1mNothing to do!\033[0m")
    else:
        backend_record_dict = input_json()  # 要求输入json格式
        for key in backend_record_dict:
            backend = key
            record = backend_record_dict[key]
            if action == "add":
                add(backend, record)
            elif action == "delete":
                delete(backend, record)
        if change_flag is True:  # 文件有修改,才进行文件更新
            # 将操作结果生效
            shutil.copy("haproxy.cfg", "old.cfg")
            shutil.copy("new.cfg", "haproxy.cfg")
            result = fetch(backend)
            output(result)  # 输出获取到的server信息


def judge_input():
    # 判断输入功能编号,执行相应步骤
    input_info = input("Your input number:").strip()
    if input_info == "1":  # 查询指定backend记录
        action = "fetch"
    elif input_info == "2":  # 添加backend记录
        action = "add"
    elif input_info == "3":  # 删除backend记录
        action = "delete"
    elif input_info == "q" or input_info == "quit":
        exit("Bye,thanks!".center(50, "#"))
    else:
        print("\033[31;1mInput error!\033[0m")
        action = None
    return action


def main():
    exit_flag = False
    while exit_flag is not True:
        global change_flag
        change_flag = False
        list_function()
        action = judge_input()
        operate(action)


if __name__ == '__main__':
    main()
View Code

我自己写的

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: liang 

import shutil

def list_show():
    print("[1] 查看haproxy.cfg 的backend信息".center(50,'#'))
    print("[2] 添加 haproxy.cfg 的backend信息".center(50,'#'))
    print("[3] 删除 haproxy.cfg 的backend信息".center(50,'#'))
    print("[4] 退出 按q 或者 exit 退出:>>>".center(50,'#'))
    print("#".center(50,'#'))


def select_haproxy(backend):
    rest=[]
    flag=False
    with open("haproxy.txt",'r',encoding="utf-8") as f:
        for line in f:
            line=line.strip()
            if line.startswith("backend") and line == "backend " + backend:
                flag=True
                continue
            if flag and line.startswith("backend"):
                flag=False
                break
            if flag and line.strip():
                rest.append(line.strip())
    return rest



def Write_in(backend,record_list):
    with open("haproxy.txt", 'r', encoding="utf-8") as f, open("haproxy2.txt", 'w', encoding="utf-8") as f2:
        flag=False
        for line in f:
            if line.strip().startswith("backend") and line.strip() == "backend " + backend:
                flag=True
                f2.write(line)
                for f2_line in record_list:
                    f2.write(" " * 4 + f2_line + "\n")
                continue
            if flag and line.strip().startswith("backend"):
                flag=False
                f2.write(line)
                continue
            if not flag and line.strip():
                f2.write(line)

    pass
def add_func(backend,record):
    global change_flag
    rest=select_haproxy(backend) #查找这个记录是否存在
    if not rest:  ### backend 不存在  record 不存在
        with open("haproxy.txt",'r',encoding="utf-8") as f,open("haproxy2.txt",'w',encoding="utf-8") as f2:
            for line in f:
                f2.write(line)
            f2.write("\nbackend " + backend + "\n")
            f2.write(" " * 4 + record + "\n")
        print("backend不存在record不存在 写入成功")
        change_flag = True
    else:
        # backend 存在  recore 存在
        if record in rest:
            print("你输入的已经存在数据库中!!!")
            change_flag=False
        else:
            # backend 存在 recore 不存在
            rest.append(record)
            Write_in(backend,rest)
            print("backend 存在 recore 不存在 写入成功")
            change_flag=True
    return change_flag

def delete_func(backend,record):
    global change_flag
    rest=select_haproxy(backend)
    if not rest:
        # backend 不存在 recore 不存在
        print("你输入的域名不存在!!!!")
        change_flag=False
    else:
        #backend 存在 recore 存在
        if record in rest:
            rest2=rest.remove(record)
            Write_in(backend,rest2)
            print("backend 存在 recore 存在 删除成功!!!")
            change_flag=True
        else:
            #backend 存在 recore 不存在
            print("你输入的recore 不存在")
            change_flag=False
    return change_flag

def output(servers):
    #输入 servers 信息
    print("server 的信息如下:>>>".center(50,'#'))
    for server in servers:
        print("\033[34;1m%s\033[0m" %servers)
    print("end ".center(50,'#'))


# def input_json():
#     # 判断输入,要求为json格式
#     flag=False
#     while flag is not True:
#         aa={"www.baidu.com":"'server':192.168.10.1"}
#         backend_inpit=input("请输入需要添加的信息:请用字典格式方式例如{%s} "%aa).strip()
#         try:
#             backend_inpit=eval(backend_inpit)
#         except Exception as e:
#             print("\033[31;1m请输入以上格式!!!!!\033[0m")
#             continue
#         flag=True
#     return flag
#


def operate(action):
    global change_flag
    if action == "select_haproxy":
        backend_info=input("请输入你要查询的域名:例如:www.baidu.com:>>")
        rest=select_haproxy(backend_info)
        if rest:
            output(rest)
        else:
            print("你输入的没有在数据库中查询不到!!!!")
    elif action == None:
        print("不能输入空")
    else:
        aa = {"www.baidu.com": "'server':192.168.10.1"}
        backend_inpit = input("请输入需要添加的信息:请用字典格式方式例如{%s} " % aa).strip()
        backend_inpit = eval(backend_inpit)
        for key in backend_inpit:
            backend=key
            record=backend_inpit[key]
            if action=='add_func':
                add_func(backend,record)
            elif action=='delete_func':
                delete_func(backend,record)
            if change_flag is True:
                shutil.copy("haproxy.txt","haproxy1.txt")
                shutil.copy("haproxy2.txt","haproxy.txt")
                result = select_haproxy(backend)
                output(result)  # 输出获取到的server信息





def input_operate():
    input_info=input("请选择你需要输入的ID号:>>>>")
    if input_info=='1':
        action= "select_haproxy"
    elif input_info=='2':
        action = "add_func"
    elif input_info=='3':
        action="delete_func"
    elif input_info == "q" and input_info=="exit":
        exit("欢迎下次再来!!!".center(50,'#'))
    else:
        print("输入错误".center(50,'#'))
        action=None
    return action



def main():
    exit_flag=False
    while exit_flag is not True:
        global change_flag
        change_flag=False
        list_show()
        action=input_operate()
        operate(action)


if __name__ == '__main__':
    main()
View Code

 

 

haproxy.cfg 文件  

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 51cto.com
    bind 0.0.0.0:80
    option httplog
    option httpclose
    option  forwardfor
    log global
    acl www hdr_reg(host) -i test01.example.com
    use_backend test01.example.com if www
backend test01.example.com
    server 100.1.7.10 100.1.7.10 weight 20 maxconn 3000
backend test.com
    server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000
    server 100.1.7.66 100.1.7.66 weight 20 maxconn 3000
    server 100.1.7.27 100.1.7.27 weight 20 maxconn 3000
    server 100.1.7.13 100.1.7.13 weight 20 maxconn 3000
    liang
backend www.test.com
    server 100.1.7.13 100.1.7.13 weight 20 maxconn 3000
View Code

 

测试结果:

########Please choice the ID of a action.#########
【1】.Fetch haproxy.cfg backend infomation.
【2】.Add haproxy.cfg backend infomation.
【3】.Delete haproxy.cfg backend infomation.
#######################End########################
Your input number:1
Input backend info:test.com
##############Match the server info:##############
server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000
server 100.1.7.66 100.1.7.66 weight 20 maxconn 3000
server 100.1.7.27 100.1.7.27 weight 20 maxconn 3000
##################################################
########Please choice the ID of a action.#########
【1】.Fetch haproxy.cfg backend infomation.
【2】.Add haproxy.cfg backend infomation.
【3】.Delete haproxy.cfg backend infomation.
#######################End########################
Your input number:2
Input backend info(json):{"test.com":"testtest.com"}
Add done
##############Match the server info:##############
server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000
server 100.1.7.66 100.1.7.66 weight 20 maxconn 3000
server 100.1.7.27 100.1.7.27 weight 20 maxconn 3000
testtest.com
##################################################
########Please choice the ID of a action.#########
【1】.Fetch haproxy.cfg backend infomation.
【2】.Add haproxy.cfg backend infomation.
【3】.Delete haproxy.cfg backend infomation.
#######################End########################
Your input number:1
Input backend info:test.com
##############Match the server info:##############
server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000
server 100.1.7.66 100.1.7.66 weight 20 maxconn 3000
server 100.1.7.27 100.1.7.27 weight 20 maxconn 3000
testtest.com
##################################################
########Please choice the ID of a action.#########
【1】.Fetch haproxy.cfg backend infomation.
【2】.Add haproxy.cfg backend infomation.
【3】.Delete haproxy.cfg backend infomation.
#######################End########################
Your input number:3
Input backend info(json):{"test.com":"testtest.com"}
Delete done
##############Match the server info:##############
server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000
server 100.1.7.66 100.1.7.66 weight 20 maxconn 3000
server 100.1.7.27 100.1.7.27 weight 20 maxconn 3000
##################################################
########Please choice the ID of a action.#########
【1】.Fetch haproxy.cfg backend infomation.
【2】.Add haproxy.cfg backend infomation.
【3】.Delete haproxy.cfg backend infomation.
#######################End########################
Your input number:4
Input error!
Nothing to do!
########Please choice the ID of a action.#########
【1】.Fetch haproxy.cfg backend infomation.
【2】.Add haproxy.cfg backend infomation.
【3】.Delete haproxy.cfg backend infomation.
#######################End########################
Your input number:3
Input backend info(json):d
Input not a json data type!
Input backend info(json):{"test01.example.com":"server 100.1.7.27 100.1.7.27 weight 20 maxconn 3000"}
########Only match backend,no need delete!########
########Please choice the ID of a action.#########
【1】.Fetch haproxy.cfg backend infomation.
【2】.Add haproxy.cfg backend infomation.
【3】.Delete haproxy.cfg backend infomation.
#######################End########################
Your input number:q
###################Bye,thanks!####################

Process finished with exit code 1

 

posted @ 2018-01-22 23:53  crazy_py  阅读(418)  评论(0编辑  收藏  举报