练手--文件的操作,字典列表的时候,字符串的处理

要求:

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

文件内容:

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
		server 100.1.7.99 100.1.7.99 weight 20 maxconn 30
        use_backend www.oldboy.org if www
		server 100.1.7.99 100.1.7.99 weight 20 maxconn 30

backend www.oldboy.org
		server 100.1.7.99 100.1.7.99 weight 20 maxconn 30

backend buy.oldboy.org
		server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000
		server 100.1.7.93 100.1.7.93 weight 20 maxconn 300

代码:

import json
import os


def index(file):
    # 输出backend
    with open(file) as f:
        print_flag = False
        for i in f.readlines():
            line = i.strip('
')
            if line.startswith('backend'):
                print(line)
                print_flag = True
            elif print_flag:
                print(line)
            elif print_flag:
                print('未找到配置!')


def bak():
    os.rename('ha.ini', 'ha.ini.l')
    os.rename('ha.ini.bak', 'ha.ini')
    os.rename('ha.ini.l', 'ha.ini.bak')


def select(backend_name):
    """
    用于查询配置文件backend信息
    :param backend_name:
    :return:
    """
    start = 0    # 找到所要查找的内容,置为1
    p_list = []  # 保存已查询到的内容
    with open('ha.ini') as fy:
        for i in fy:
            if i.startswith('backend') and start == 0:
                if backend_name in i:
                    start = 1
                    print('所查询的backend为:{}'.format(i))
                    continue
            elif i.startswith('	') and start == 1:
                p_list.append(i)
            elif i.startswith('backend') and start == 1:
                break
        if start == 0:
            print('未找到配置!')
        elif start == 1:
            print('所查找的配置为:')
            for i in p_list:
                print(i.strip('
'))


def insert(backend_name):
    """
    用于插入backend配置信息
    :param backend_name:输入的backend信息
    :return:
    """
    inp_dict = json.loads(backend_name)
    b_exs = 0    # 要插入的back是否已经存在,默认为否
    r_exs = 0    # 要插入的record是否已经存在,默认为否
    with open('ha.ini') as fy, open('ha.ini.bak', 'w') as fb:
        server, weight, maxconn = inp_dict['record']['server'], inp_dict['record']['weight'], inp_dict['record']['maxconn']
        for i in fy:
            if inp_dict['backend'] in i:
                b_exs = 1
                fb.write(i)
                fb.write('		server %s %s weight %s maxconn %s
' % (server, server, weight, maxconn))
            elif i.startswith('	') and b_exs == 1:
                a, b, c = str(server), str(weight), str(maxconn)
                if a not in i or b not in i or c not in i:
                    fb.write(i)
                elif a in i or b in i or c in i:
                    r_exs = 1
                    print('配置已存在!')
            elif i.startswith('backend'):
                b_exs = 2
                fb.write(i)
            else:
                fb.write(i)
        if r_exs == 0 and b_exs == 1:
            print('配置插入成功!')

        if b_exs == 2 or b_exs == 0:
            fb.write('
backend %s
' % inp_dict['backend'])
            fb.write('		server %s %s weight %s maxconn %s
' %
                     (inp_dict['record']['server'], inp_dict['record']['server'],
                      inp_dict['record']['weight'], inp_dict['record']['maxconn']))
            print('配置插入成功!')
    bak()


def delete(backend_name):
    """
    用于删除backend配置信息
    :param backend_name:
    :return:
    """
    inp_dict = json.loads(backend_name)
    b_is_exs = 0    # 标识backend是否存在,存在置为1
    s_is_exs = 0    # 记录backend下的配置存在的条数
    d_suc = 0       # 删除成功置为1
    with open('ha.ini') as fy, open('ha.ini.bak', 'w') as fb:
        for i in fy:
            if inp_dict['backend'] in i:
                b_is_exs = 1
                fb.write(i)
            elif i.startswith('	') and b_is_exs == 1:
                s_is_exs += 1
                a, b, c = str(inp_dict['record']['server']), str(inp_dict['record']['weight']), str(inp_dict['record']['maxconn'])
                if a in i and b in i and c in i:
                    d_suc = 1
                else:
                    fb.write(i)
            elif i.startswith('backend'):
                b_is_exs = 2
                fb.write(i)
            else:
                fb.write(i)
        if b_is_exs == 0:
            print('未找到要删除的配置!')
        if d_suc == 1:
            print('配置已删除!')
    bak()

    if s_is_exs == 1 and d_suc == 1:    # 通过第二次循环把没有配置项的backend删除
        with open('ha.ini') as fy, open('ha.ini.bak', 'w') as fb:
            for i in fy:
                if i.startswith('backend') and inp_dict['backend'] in i:
                    pass
                else:
                    fb.write(i)
        bak()

    with open('ha.ini.bak', 'a') as fr:
        fr.write('		server %s %s weight %s maxconn %s
' %
                 (inp_dict['record']['server'], inp_dict['record']['server'],
                  inp_dict['record']['weight'], inp_dict['record']['maxconn']))


def main():
    """
    主调用函数
    :return:
    """
    print('原文件backend内容:')
    index('ha.ini')
    print("""请选择操作:
    1、获取ha记录
    2、增加ha记录
    3、删除ha记录
    4、退出
    """)
    choice_flag = True
    while choice_flag:
        choice = input('请输入操作序号:').strip()
        if choice == '1':
            r = input('请输入backend:').strip()
            select(r)
        elif choice == '2':
            i = input('请输入要新加的记录:').strip()
            insert(i)
        elif choice == '3':
            i = input('请输入要删除的记录:').strip()
            delete(i)
        elif choice == '4':
            break
        else:
            print('请正确选择!')


if __name__ == '__main__':
    main()

  

原文地址:https://www.cnblogs.com/wumingxiaoyao/p/6504194.html