查询、增加、删除haproxy配置文件内容 python

本文介绍了一个简单的HAProxy配置管理系统,包括查询、添加和删除后端服务器配置的功能。通过Python脚本实现了对HAProxy配置文件的有效管理。

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

需求:

1、查
    输入:www.lzh.org
    获取当前backend下的所有记录

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

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


2.文件如下:

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 lzh.org
        bind 0.0.0.0:80
        option httplog
        option httpclose
        option  forwardfor
        log global
        acl www hdr_reg(host) -i www.lzh.org
        use_backend www.lzh.org if www

backend www.lzh.org
        server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000


3.实现如下:

__author__ = "craneliu"
import os

#定义查询域名记录的函数
def query_dns(dns):
    with open("haproxy","r",encoding="utf-8") as f:
        find_flog=False                 #定义是否查到记录的标记,True代表找到,False代表没有找到
        dns_record=[]                    #定义列表保存查找到的记录
        for line in f.readlines():
            if line.startswith("backend %s" %(dns)):
                find_flog=True
                dns_record.append(line)        #保存查找到的backend第一行记录
                continue
            if line.startswith("backend"):#这句的作用是避免查找到多条backend开头的记录
                find_flog=False
            if find_flog:
                dns_record.append(line)   #保存查找到的backend的第二行记录
        #打印查找到的内容
        if dns_record:
            print("查找到的内容如下:================")
            for dns_content in dns_record:
                print(dns_content)
        else:
            print("很抱歉!!!你查找的内容不存在。。。")
    return dns_record                        #返回供下面的函数调用结果

#定义新增backend的配置函数
def add_backend(**add_dns):
    arg={}
    arg['backend']=add_dns.get('backend')
    arg['record']=add_dns.get('record')

    with open('haproxy','a+',encoding='utf-8') as f:
        #判断检查要添加的记录是否存在
        if not query_dns(arg['backend']):
            write_content = "\nbackend %s\n        server %s weight %s maxconn %s" % (
                arg['backend'], arg['record']['server'], arg['record']['weight'], arg['record']['maxconn'])
            f.write(write_content)
            print("添加新的记录成功")
        else:
            print("很抱歉!!!你添加的记录已经存在")

#定义删除backend的函数
def del_backend(**kwargs):
    arg_del={}
    arg_del['backend']=kwargs.get('backend')
    arg_del['record'] = kwargs.get('record')
    with open("haproxy","r+",encoding="utf-8") as f,open("haproxy_new","w+",encoding="utf-8") as f_new:
        #检查是否已经存在相同的内容
        query_result=query_dns(arg_del['backend'])
        if query_result:
            del_file=True
            old_file_list=[]               #旧文件的内容保存到列表中,如果需要删除,则删除列表的内容,再写入新文件,从而达到删除的目的
            for line in f.readlines():
                old_file_list.append(line)
            print("------------------------------------------------")
            for del_content in query_result:
                old_file_list.remove(del_content)
            for line in old_file_list:
                f_new.write(line)                      #写入到新文件
            else:
                print("正在删除....")

        else:
            print("你删除的记录不存在")
    if del_file:                             #重命名文件
        os.rename('haproxy', 'haproxy_bak')
        os.rename('haproxy_new', 'haproxy')
        os.remove('haproxy_bak')
        print("删除成功")



choice=input("请输入你想要的操作:\n1 查询域名记录\n2 增加新的bakcend配置\n3 删除旧的域名配置\n")
if choice.isdigit():
    choice=int(choice)
    if choice>=1 and choice<=3:
        #查询域名的记录
        if choice==1:
            input_dns=input("请输入你需要查询的域名:")
            query_dns(input_dns)
            #增加新的dns记录
        elif choice==2:
            print("请输入你要增加的backend配置")
            input_dict=input("arg=")
            input_dict=eval(input_dict)
            add_backend(**input_dict)
            #删除backend的记录
        else:
            print("请输入你需要删除的backend配置")
            input_del_dict=input("arg=")
            input_del_dict=eval(input_del_dict)
            del_backend(**input_del_dict)
    else:
        print("invalid option...")
else:
    print("Only digital numbers is required.....")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值