首页 > 编程语言 >Python 修改ha配置文件

Python 修改ha配置文件

时间:2023-06-21 11:36:51浏览次数:46  
标签:ha 配置文件 Python server write record 100.1 backend

Python 修改ha配置文件

任务要求

1、用户输入字符串
    {"backend": "test.oldboy.org","record":{"server": "100.1.7.9","weight": 20,"maxconn": 30}}

2、在对应的backend下,添加一条新记录
    backend不存在时,创建

3、删除一条记录
    backend没有值时,删除   

4、查询一个backend记录

流程图

代码

1、主文件

import json
import os
import sys
 
 
def login(func):
    def loginning(*args,**kwargs):
        # 验证用户帐号和密码函数
        # global name
        lock = "lock.txt"
        loginfile = "password.txt"
        login_info = 0
        i = 0
 
        while i < 3 and login_info == 0:
            name = input("Please input your name: ")
            with open(lock, "r") as f:
                for line in f:
                    # if name in line:
                    if name == line.strip():
                        sys.exit('\033[32:1m用户 %s 已经被锁定\033[0m' % name)
            password = input("Please input password: ")
            with open(loginfile, "r") as f:
                for line in f:
                    user_file, pass_file = line.split()
                    if user_file == name and pass_file == password:
                        # print("Bingo!")
                        login_info = 1
                        continue
                else:
                    if login_info != 1:
                        print("You name or password is error!")
                        i += 1
        else:
            if i == 3 and login_info == 0:
                f = open(lock, "a")
                f.write(name + "\n")
                f.close()
                print('\033[32:1m用户 %s 已经被锁定\033[0m' % name)
        return func(*args, **kwargs)
    return loginning
 
 
def fetch(backend):
    backend_title = 'backend %s' % backend
    record_list = []
    with open('ha') as obj:
        flag = False
        for line in obj:
            line = line.strip()
            if line == backend_title:
                flag = True
                continue
            if flag and line.startswith('backend'):
                flag = False
                break
 
            if flag and line:
                record_list.append(line)
 
    return record_list
 
 
def add(dict_info):
    backend = dict_info.get('backend')
    record_list = fetch(backend)
    # print(record_list)
    sign = 1
    backend_title = "backend %s" % backend
    current_record = "server %s %s weight %d maxconn %d" % (dict_info['record']['server'], dict_info['record']['server'], dict_info['record']['weight'], dict_info['record']['maxconn'])
    if not record_list:
        record_list.append(backend_title)
        record_list.append(current_record)
        with open('ha') as read_file, open('ha.new', 'w') as write_file:
            flag = False
            for line in read_file:
                write_file.write(line)
            for i in record_list:
                if i.startswith('backend'):
                    write_file.write(i + '\n')
                else:
                    write_file.write("%s%s\n" % (8 * " ", i))
    else:
        record_list.insert(0, backend_title)
        # print(record_list)
        if current_record not in record_list:
            record_list.append(current_record)
            with open('ha') as read_file, open('ha.new', 'w') as write_file:
                flag = False
                has_write = False
                for line in read_file:
                    line_strip = line.strip()
                    if line_strip == backend_title:
                        flag = True
                        continue
                    if flag and line_strip.startswith('backend'):
                        flag = False
                    if not flag:
                        write_file.write(line)
                    else:
                        if not has_write:
                            for i in record_list:
                                if i.startswith('backend'):
                                    write_file.write(i + '\n')
                                else:
                                    write_file.write("%s%s\n" % (8 * " ", i))
                        has_write = True
        else:
            sign = 0
            print("该IP记录已存在,请重新确认信息")
    if sign == 1:
        move_filename()
 
 
def remove(dict_info):
    backend = dict_info.get('backend')
    record_list = fetch(backend)
    backend_title = "backend %s" % backend
    current_record = "server %s %s weight %d maxconn %d" % (dict_info['record']['server'], dict_info['record']['server'], dict_info['record']['weight'], dict_info['record']['maxconn'])
    if not record_list:
        print("该backend记录不在配置文件中,请检测后重新输入!")
        return
    else:
        if current_record not in record_list:
            print("该主机配置记录不正确,请检测后重新输入!")
            return
        else:
            del record_list[record_list.index(current_record)]
            if len(record_list) > 0:
                record_list.insert(0, backend_title)
        with open('ha') as read_file, open('ha.new', 'w') as write_file:
            flag = False
            has_write = False
            for line in read_file:
                line_strip = line.strip()
                if line_strip == backend_title:
                    flag = True
                    continue
                if flag and line_strip.startswith('backend'):
                    flag = False
                if not flag:
                    write_file.write(line)
                else:
                    if not has_write:
                        for i in record_list:
                            if i.startswith('backend'):
                                write_file.write(i + '\n')
                            else:
                                write_file.write("%s%s\n" % (8 * " ", i))
                    has_write = True
    move_filename()
 
 
def move_filename():
    for file in os.listdir('.'):
        if file == "ha.bak":
            os.remove(file)
    os.rename('ha', 'ha.bak')
    os.rename('ha.new', 'ha')
    print("操作成功")
 
 
def show():
    # 显示信息函数
    print("*****************************")
    print("1、获取ha记录")
    print("2、增加ha记录")
    print("3、删除ha记录")
    print("4、退出系统")
    print("*****************************")
    return


@login
def main():
    while True:
        # 输出显示信息
        show()
 
        num = input('请输入序号:')
 
        if num == '1':
            data = input('请输入内容:')
            ret = fetch(data)
            for i in ret:
                print(i)
        elif num == '4':
            sys.exit("欢迎再次使用haproxy修改系统")
        else:
            data = input('请输入内容:')
            dict_data = json.loads(data)
            if num == '2':
                add(dict_data)
            elif num == '3':
                remove(dict_data)
            else:
                print("你输入的操作系列号有误!请重新输入。")
 
 
if __name__ == '__main__':
    main()

2、用户帐号密码文件

# password.txt
evescn gmkk
gmkk 12321

3、ha配置文件

# ha配置文件
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.119 100.1.7.119 weight 20 maxconn 30
        server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
        server 100.1.7.19 100.1.7.19 weight 20 maxconn 30
        server 100.1.7.12 100.1.7.12 weight 20 maxconn 30
 
backend buy.oldboy.org
        server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000 

运行结果

1、查询记录

Please input your name: evescn
Please input password: gmkk
*****************************
1、获取ha记录
2、增加ha记录
3、删除ha记录
4、退出系统
*****************************
请输入序号:1
请输入内容:www.oldboy.org
server 100.1.7.119 100.1.7.119 weight 20 maxconn 30
server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
server 100.1.7.19 100.1.7.19 weight 20 maxconn 30
server 100.1.7.12 100.1.7.12 weight 20 maxconn 30
*****************************

2、增加记录

*****************************
1、获取ha记录
2、增加ha记录
3、删除ha记录
4、退出系统
*****************************
请输入序号:2
请输入内容:{"backend": "test.oldboy.org","record":{"server": "100.1.7.9","weight": 20,"maxconn": 30}}
操作成功
*****************************
 
# ha配置文件
.......
backend buy.oldboy.org
        server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000
 
backend test.oldboy.org
        server 100.1.7.9 100.1.7.9 weight 20 maxconn 30 

3、删除记录

*****************************
1、获取ha记录
2、增加ha记录
3、删除ha记录
4、退出系统
*****************************
请输入序号:3
请输入内容:{"backend": "buy.oldboy.org","record":{"server": "100.1.7.90","weight": 20,"maxconn": 3000}}
操作成功
*****************************
 
 
# ha配置文件
......
backend www.oldboy.org
        server 100.1.7.119 100.1.7.119 weight 20 maxconn 30
        server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
        server 100.1.7.19 100.1.7.19 weight 20 maxconn 30
        server 100.1.7.12 100.1.7.12 weight 20 maxconn 30
 
backend test.oldboy.org
        server 100.1.7.9 100.1.7.9 weight 20 maxconn 30

标签:ha,配置文件,Python,server,write,record,100.1,backend
From: https://www.cnblogs.com/evescn/p/17495829.html

相关文章

  • Porting Code to Python 3 with 2to3
    参考https://www.cmi.ac.in/~madhavan/courses/prog2-2012/docs/diveintopython3/porting-code-to-python-3-with-2to3.html......
  • ChatGPT免费入口-在线体验AI科技成果
    大家好!我很激动地向你们介绍一个令人惊叹的AI科技成果-ChatGPT。这是一个由OpenAI开发的先进语言模型,它利用深度学习和自然语言处理技术,能够与用户进行智能对话,并提供帮助、回答问题和解决难题。**体验无处不在的AI智能:**如果你对人工智能感兴趣,或者想要亲身体验最新的AI技术......
  • 关于在Redhat-7-linux-系统-Apache-2.4.6-版本上部署多个版本的yum仓库-的配置文件写
    背景:云上有一台内部yum服务器,操作系统及版本信息为:RedHatEnterpriseLinuxServerrelease7.9(Maipo)上面每天会同aws仓库官网同步repo,版本也自然是 RedHatEnterpriseLinuxServerrelease7现在需要临时增加Redhat8.的仓库,(默认Redhat8也是有内部repo仓库的,只是在......
  • ChatGPT免费入口-在线体验AI科技成果
    **ChatGPT免费入口-在线体验AI科技成果**大家好!我非常兴奋地向大家介绍一个令人惊叹的AI科技成果-ChatGPT。作为一款由OpenAI开发的高级语言模型,它利用深度学习和自然语言处理技术,能够与用户进行智能对话,并提供帮助、回答问题和解决难题。**无处不在的AI智能体验:**如果你对人......
  • 免费ChatGPT网站——让你畅所欲言的智能交流平台
     大家好!今天我要向大家推荐一个令人惊叹的智能交流平台——免费ChatGPT网站。无论你是热衷于与人交流、分享经验或者寻找答案,这个网站都将成为你的最佳选择。ChatGPT简介ChatGPT是由OpenAI开发的一种基于深度学习的自然语言处理模型。通过使用人工智能技术,它能够理解并生成与......
  • 免费ChatGPT网站:解锁无限创造力与智慧对话的新时代
    在当今快速发展的科技领域,人工智能(AI)正以惊人的速度改变着我们的生活。其中,自然语言处理(NLP)技术的突破引发了全球范围内的关注和讨论。作为前沿的NLP应用之一,ChatGPT已经成为了解决问题、提供信息以及增强创造力的重要工具。ChatGPT-掌握智能对话的钥匙如果你渴望与一个真实、智......
  • 根据ubuntu:20.04制作python环境docker镜像
    因为有个算法是python写的,要在服务器上调用,之前是直接根据jdk镜像制作的环境,现在要装python,jdk双环境,只能自己制作一个镜像出来了,命令如下FROMubuntu:20.04ENVTZ=Asia/ShanghaiENVLANGC.UTF-8RUNmv/etc/apt/sources.list/etc/apt/sources.list.bakCOPYsources.li......
  • 《Red Hat Linux命令速查》—— 带你玩转字符游戏
    命令行管理,一个玩转字符的战场!忽隐忽现的光标  神秘莫测的符号  闪转腾挪的玄机  直捣黄龙的快意能领略这一切的人,只有你——深谙命令行管理之道的系统管理员和软件开发人员!命令行之于优秀的系统管理员、软件开发人员,恰如武林高手必须修炼的内功心法,一旦掌握,不仅可以大大提高......
  • 免费ChatGPT网站——让你畅所欲言的智能交流平台
     大家好!今天我要向大家推荐一个令人惊叹的智能交流平台——免费ChatGPT网站。无论你是热衷于与人交流、分享经验或者寻找答案,这个网站都将成为你的最佳选择。ChatGPT简介ChatGPT是由OpenAI开发的一种基于深度学习的自然语言处理模型。通过使用人工智能技术,它能够理解并生成与......
  • 免费ChatGPT网站:解锁无限创造力与智慧对话的新时代
    在当今快速发展的科技领域,人工智能(AI)正以惊人的速度改变着我们的生活。其中,自然语言处理(NLP)技术的突破引发了全球范围内的关注和讨论。作为前沿的NLP应用之一,ChatGPT已经成为了解决问题、提供信息以及增强创造力的重要工具。ChatGPT-掌握智能对话的钥匙如果你渴望与一个真实、智......