Python3学习之路~2.10 修改haproxy配置文件

需求:

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
            }
        }
View Code

原配置文件:

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:Zheng Na
# 参考:https://www.cnblogs.com/1dreams/p/6880205.html
# 代码缺陷:
# 对每次输入都没有做校验,一旦格式错误就报错
# 某些功能未实现
# 将文件先变成一个列表,如果文件很大就没办法了

import json

f = open('haproxy.txt','r',encoding="UTF-8")
f_new = open('haproxy_new.txt','w',encoding="UTF-8")
#将文件内容转换为一个列表,并定义一个变量。
f_list =f.readlines()
#print(f_list)
process_list = ["获取ha记录","增加ha记录","删除ha记录"]
print("可选操作如下:".center(20,'*'))
for index,item in enumerate(process_list):
    print(index+1,item)
num = int(input("请输入操作序号:"))

if num == 1:
    read = input("请输入backend:") # 如输入:www.oldboy.org
    # 利用字符串拼接,定义一个变量,-----backend所在的行。
    backend_title = "backend %s\n" % read
    if backend_title in f_list:
        index_bt = f_list.index(backend_title)
        print(f_list[index_bt],f_list[index_bt+1])  #没有判断backend下面有多少行,万一有很多行呢?
    else:
        print("您查找的内容不存在!")

if num ==2:
    read = input("请输入要新加的记录:") # 如: {"backend": "test.oldboy.org","record":{"server": "100.1.7.9","weight": 20,"maxconn": 30}}
    # 将read字符串转换成 字典类型 方法1
    read_dict = json.loads(read)
    # 将read字符串转换成 字典类型 方法2 有点儿low
    # read_dict = eval(read)

    # 通过列表计数器来判断输入的内容是否在列表中存在,如果计数器为0则不存在,如果计数器不为0则存在。
    # 不存在则添加,存在则不添加。
    backend_title = "backend %s\n" % read_dict["backend"]
    f_find = f_list.count(backend_title)
    if f_find == 0:
        for line in f_list:
            f_new.write(line)
        f_new.write("\n\n")
        f_new.write(backend_title)
        f_new.write("        server %s %s weight %s maxconn %s"\
                    %(read_dict["record"]["server"],read_dict["record"]["server"],\
                      read_dict["record"]["weight"],read_dict["record"]["maxconn"]))
    else:
        # # 如果已经存在,
        #         # 则在此节点下添加根据用输入构造出的记录,例如:
        #             server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
        #     # (可选)可以再对节点下记录进行判断是否已经存在
        # 未实现此功能
        print("您要添加的记录已存在!")

if num == 3:
    read = input("请输入要删除的记录:")  # 如: {"backend": "test.oldboy.org","record":{"server": "100.1.7.9","weight": 20,"maxconn": 30}}
    # 将read字符串转换成 字典类型 方法1
    read_dict = json.loads(read)
    # 将read字符串转换成 字典类型 方法2 有点儿low
    # read_dict = eval(read)

    # 通过列表计数器来判断输入的内容是否在列表中存在,如果计数器为0则不存在,如果计数器不为0则存在。
    backend_title = "backend %s\n" % read_dict["backend"]
    f_find = f_list.count(backend_title)
    # 存在则删除
    #     #去配置文件中找到指定的节点,并在删除指定记录,如:
    #     backend test.oldboy.org
    #          server 100.1.7.10 100.1.7.10 weight 20 maxconn 3000
    #          server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000   # 删除掉
    #
    #     # (可选)如果backend下所有的记录都已经被删除,那么将当前 backend test.oldboy.org 也删除掉。
    #  未实现此功能
    if f_find != 0:
        index_bt = f_list.index(backend_title)
        f_list.pop(index_bt)
        f_list.pop(index_bt) #删掉index_bt位置元素后,index_bt+1位置元素自动向前占据index_bt位置
        for line in f_list:
            f_new.write(line)
    else:
        print("您要删除的记录不存在!")

f.close()
f_new.close()
菜鸟版
# Author:Zheng Na
# 参考:https://www.cnblogs.com/Ian-learning/p/7895004.html
import json

def recd_read():
    # 用来读取数据
    read = input("请输入backend:")  # 如输入:www.oldboy.org
    with open('haproxy.txt', 'r', encoding='UTF-8') as f:  # 用只读的形式打开
        for line in f:
            if 'backend' in line:
                backend_title = "backend %s\n" % read
                if line == backend_title:
                    return print(f.readline())
    return print("您查找的内容不存在!")

def recd_add():
    # 用来增加数据,暂时没有加入判断输入数据类型的内容
    read = input(
        "请输入要新加的记录:")  # 如: {"backend": "test.oldboy.org","record":{"server": "100.1.7.9","weight": 20,"maxconn": 30}}
    # 将read字符串转换成 字典类型 方法1
    read_dict = json.loads(read)
    # 将read字符串转换成 字典类型 方法2 有点儿low
    # read_dict = eval(read)
    with open('haproxy.txt', 'r+', encoding='UTF-8') as f:  # 用可以读写的形式打开
        for line in f:
            if 'backend' in line:
                backend_title = "backend {website}\n".format(website=read_dict['backend'])
                if line == backend_title:
                    return print("您要添加的记录已存在!")
        f.write("\n\n")
        f.write(backend_title)
        f.write("\t\tserver {} {} weight {} maxconn {}\n" \
                .format(read_dict["record"]["server"], read_dict["record"]["server"], \
                        read_dict["record"]["weight"], read_dict["record"]["maxconn"]))
    return print('添加记录成功!')

def recd_delete():
    # 用来删除数据
    read = input(
        "请输入要删除的记录:")  # 如: {"backend": "test.oldboy.org","record":{"server": "100.1.7.9","weight": 20,"maxconn": 30}}
    # 将read字符串转换成 字典类型
    read_dict = json.loads(read)
    flag = 0
    with open('haproxy.txt', 'r', encoding='UTF-8') as f, \
            open('haproxy_tmp.txt', 'w', encoding='UTF-8') as f_tmp:
        backend_title = "backend {}\n".format(read_dict['backend'])
        for line in f:
            backend_title = "backend {}\n".format(read_dict['backend'])
            if line == backend_title:
                flag = 1
                f.readline()
                continue
            f_tmp.write(line)

    if flag == 0:
        return print("您要删除的记录不存在!")
    else:
        with open('haproxy.txt', 'w', encoding='UTF-8') as f, \
                open('haproxy_tmp.txt', 'r', encoding='UTF-8') as f_tmp:
            for line in f_tmp:
                f.write(line)
    return print('记录已被删除!')

choice_recd = ['add', 'delete', 'read', 'quit']  # 用来判断输入的内容对不对

while True:
    choice = input("Please choose 'add', 'delete', 'read','quit'>>>")
    if choice in choice_recd:  # 判断输入的内容对不对
        if choice == 'add':
            recd_add()
        elif choice == 'read':
            recd_read()
        elif choice == 'delete':
            recd_delete()
        elif choice == 'quit':
            exit("您已退出程序")
进阶版
# Author:Zheng Na
# 参考:https://www.cnblogs.com/Ian-learning/p/7895004.html

import shutil
import json

def list_function():
    print("Please choice the ID of a action.".center(50, "#"))
    print("【1】.Fetch haproxy.cfg backend infomation.")
    print("【2】.Add haproxy.cfg backend infomation.")
    print("【3】.Delete haproxy.cfg backend infomation.")
    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开头
            if line.strip().startswith("backend") and line.strip() == "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):
    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)  # 查找是否存在记录
    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(" " * 8 + 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("\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()
大神版

 

转载于:https://www.cnblogs.com/zhengna/p/9202239.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值