Small master switch to the road environment of -13-haproxy file modification

Foreword


The dive a few days because the boss called to go on a business trip for 2 days, then see ti9 a fall Saturday, sin a sin. The rush to catch up on work. Then think about the big job, and find python whole stack of high-quality resources. We hope to have greatly improved my code to force.

Work requirements


A configuration file to txt

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

Primarily to modify the data backend of the bottom. Basic requirements:
1. search: Enter URL: As the next line can be printed www.oldboys.com sever, ip, weight, maxconn.
2. Create: Enter a dictionary ({ 'backend': 'www.baidu.org ', 'record': { 'server': '100.1.7.9', 'weight': 20, 'maxconn': 30}}) you can be appended to a file inside.
3. Delete: Enter a URL to delete all of its relevant content.


Source

def info_message(message):#用于输出————————————info of **————————————
    print('\33[33;1minfo of %s\33[0m'.center(50,'-')%message)

def continue_process() :#用于询问是否继续
   choice = input('do you want to continue to operate the file again or exit this process? y/any other key.')
   if choice.lower() == 'y':
       pass
   else:
        exit()


def search_process():#搜索过程
    search_address = input('please input the search address:\t')
    if  search_address in dict_file.keys():#判断搜索网站是否在临时字典里
        info_message(search_address)#输出————————————info of website————————————,以后不再注释
        print(dict_file[search_address])
    else:
        print("search address don't exist or invalid input.")

def add_process_input():
    add_address = input('\33[32;1mplease input the info of your haproxy.\33[0m')
    try:
        info = eval(add_address)#将输入字符串变成字典
        if info['backend'] not in dict_file.keys():
            file_add_info = '\nbackend {backend}\nsever {sever} weight {weight} maxconn {maxconn}'\
                            .format(backend=info['backend'],
                             sever=info['record']['server'],
                             weight=info['record']['weight'],
                             maxconn=info['record']['maxconn'])
            print('\33[32;1m successfully added\32[31')
            return file_add_info#返回要输入到文件里的值
        else:
            print('\33[32;1mthe backend that you have input now has exists.\33[0m')
            return 'continue'#若错误输入返回continue字符串在主函数判断。


    except  Exception :
        print('\33[31;01minvalid input\33[0m')
        return 'continue'
# add_info = add_process_input()
# print(add_info)
def del_process(filename):
    del_website = input('please input the website that you want to delete.')
    filename.seek(0)
    del_list = filename.readlines()#把文件所有值输入到临时列表里
    if 'backend %s\n'%del_website not in del_list:#判断输入值是否在文件里
        print('the website do not exist or wrong input.')
    else:
        del_index =del_list.index('backend %s\n'%del_website)#提取要删除对象的index
        del del_list[del_index]#删除backend website
        del del_list[del_index]#删除所含内容
        filename.seek(0)
        filename.truncate(0)#清空文件
        for d in del_list:#将列表的值写入文件
            filename.write(d)
        info_message(delete)
        print('\33[32;1m successfully deleted\32[31')
#主程序部分
with open("haproxy", "a+", encoding="utf-8") as file_haproxy: # a+模式打开haproxy文件     file_haproxy.seek(0)
    while True:
        dict_file = {}
        file_haproxy.seek(0)
        for line in file_haproxy:
            if line.startswith('backend'):
                dict_file[line.strip().split()[1]] = file_haproxy.readline().strip()
        print('please input choose the option.'.center(50,'*'))
        choice = input('1.search\n2.add\n3.delete\n4.quit\n>>:')

        if choice == '1':
            search_process()
            continue_process()

        elif choice == '2':
            add_info = add_process_input()
            if add_info == 'continue':
                continue
            print(add_info)
            file_haproxy.write(add_info)
            file_haproxy.flush()
            continue_process()
        elif choice == '3':
            re = del_process(file_haproxy)
            continue_process()

        elif choice == '4':
            exit()

 

 

 

结果


经过测试程序正常运行,不想贴了。

Guess you like

Origin www.cnblogs.com/negu/p/11372527.html