Python day2 修改haproxy配置文件 作业

本文介绍了一个使用Python编写的简易HAProxy配置管理系统。该系统具备搜索、添加和删除后端服务器的功能,通过简单的命令行交互即可完成操作。适用于需要频繁调整负载均衡配置的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原配置文件
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

原配置文件
python代码
__author__ = "OneTrainee"


def show_red(show_str):
    print("\033[3;31m{}\33[0m".format(show_str))


def search():
    """ 搜索信息 """
    website = input("please enter the url you want to query: ")
    if website in file_content.keys():
        show_result("查询信息")
        show_red(file_content[website])
    else:
        show_red("sorry,the information you want to inquire could not be founded!")


def delete():
    """ 删除信息"""
    show_result("可删除的网页");
    for name in file_content.keys():
        print(name)
    user_order = input("请输入你想删除的url")
    if user_order in file_content.keys():
        with open("haproxy", "a+", encoding='utf-8') as Handle_file:
            Handle_file.seek(0)
            lines = Handle_file.readlines()
            index = lines.index("backend {}\n".format(user_order))
            del lines[index]
            del lines[index]
            Handle_file.seek(0)
            Handle_file.writelines(lines)
        show_red("删除网页成功")
    else:
        show_red("该网页不存在")


def add():
    """ 添加信息 """
    # {'backend': 'www.baidu.org','record':{'server': '100.1.7.9','weight': 20,'maxconn': 30}}
    add_str = input("输入你想添加的信息: ")
    add_dict = eval(add_str)
    with open("haproxy","a",encoding='utf-8') as f:
        f.write("\nbackend {} \n\t\tserver {} weight {} maxconn {}".format(add_dict['backend'],
                                                              add_dict['record']['server'],
                                                              add_dict['record']['weight'],
                                                              add_dict['record']['maxconn']))


def if_continue():
    """ 询问是否继续 """
    if_cont = input("Do you want to continue ? [y/n]")
    if if_cont == 'y':
        pass
    else:
        exit()


def show_result(show_str):
    """ 显示特定的颜色 """
    print("\033[34;1m{}\033[0m".format(show_str).center(50, '-'))


while True:
    """ 开始先来读取文件内容 """
    file_content = {}
    with open("haproxy", "r", encoding='utf-8') as handle_file:
        for line in handle_file:
            if "backend" in line and "use_backend" not in line:
                file_content[line.split()[1]] = handle_file.readline().strip()

    """ 显示用户选择 """
    user_choice = input("search\\delete\\add\\quit? ")

    """ 来判断用户选择 """
    if user_choice == "quit":
        show_red("软件已退出")
        exit()
    elif user_choice == "search":
        search()
        if_continue()
    elif user_choice == 'add':
        add()
        if_continue()
    elif user_choice == 'delete':
        delete()
        if_continue()
    else:
        show_red("请输入正确指令")
        if_continue()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值