博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python之路,Day28 - Python基础-修改haproxy配置文件
阅读量:2047 次
发布时间:2019-04-28

本文共 4369 字,大约阅读时间需要 14 分钟。

小练习,python真的要多练习。

根据需求完成haproxy.conf配置文件的查询,新建,删除等操作。

需求:

1、查

    输入:www.oldboy.org
    获取当前backend下的所有记录

2、新建

    输入:
        arg = {
            'bakend': 'www.oldboy.org',
            'record':{
                'server': '100.1.7.9',
                'weight': 20,
                'maxconn': 30
            }
        }

3、删除

    输入:
        arg = {
            'bakend': 'www.oldboy.org',
            'record':{
                'server': '100.1.7.9',
                'weight': 20,
                'maxconn': 30
            }
        }

 

配置文件:

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

 代码:

#!/usr/bin/env python# _*_coding:utf-8_*_''' * Created on 2018/8/27 * @author: SJ'''import os#查询def select(domain):    result_list = []     #存放查询的结果    select_flag = False   #定义查询结果标志位False    with open('haproxy.conf','r',encoding='utf-8') as f:        for line in f:            # if 语句顺序进行,当前条件判断完,进入下一判断            if line.strip()=='backend %s' % domain:  #找到backend www.oldboy.org                flag = True                continue            if line.strip().startswith('backend '): #找到下一个 backend www.xxx.com部分结束.截取其中部分                flag = False            if flag == True:     #截取其中部分                result_list.append(line.strip())        print(result_list)    if result_list==[]:        print('对不起,您查询的网址不存在!')    else:        return  result_list#新增def add(info):    arg = eval(info)   #将输入的字符串转变为字典    # 根据key值调用value,并赋值    backend_title = arg.get('backend')    context_title = 'backend %s' %(backend_title)    record_title = arg['record']    context_record = 'server %s %s weight %s maxconn %s' % (record_title['server'],record_title['server'],record_title['weight'],record_title['maxconn'])    find_flag =False  #设置新增标志位    with open('haproxy.conf','r',encoding='utf-8') as f:        for line in f:            if line.strip()=='backend %s' % backend_title:                find_flag =True                continue            if find_flag == True:                print('已经存在!')            if line.strip().startswith('backend'):                flag = False            else:                with open('haproxy.conf','r',encoding='utf-8') as f ,\                      open('haproxy.conf_new','w+',encoding='utf-8') as f_new:                    for line in f:                        f_new.write(line)   #复制原始一份文件                    f_new.write('\n'+context_title+'\n')                    new_backend = ' '*8+context_record+'\n'   #赋值                    f_new.write(new_backend)   #写入文件                    print('新建成功!')    #将原始文件删除    os.rename('configuration','configuration.bak')    os.rename('configuration.bak','configuration')    os.remove('configuration.bak')#删除def delete(dict_info):    del_backend = dict_info['backend']  #抓取value    del_record= dict_info['record']   #抓取value    context_title = 'backend %s' % (del_backend)    context_record='server %s %s weight %s maxconn %s' %(del_record['server'],del_record['server'],del_record['weight'],del_record['maxconn'])    fetch_list = select(del_backend)    if not fetch_list:        return    else:        if context_record not in fetch_list:            print('你输入的信息不存在!')            return        else:            fetch_list.remove(context_record)        with open('haproxy.conf','r') as read_obj,\              open('haproxy.conf.new','w') as write_obj:            flag =False            has_write = False            for line in read_obj:                if line.strip()==context_title:                    flag = True                    continue                if flag and line.startswith('backend '):                    flag=False                if flag == True:                    if not has_write:                        print(fetch_list)                        for new_line in fetch_list:                            temp = '%s%s\n' % (' '*8,new_line)                            write_obj.write(temp)                    has_write = True                else:                    write_obj.write(line)        os.rename('configuration','configuration.bak')        os.rename('configuration.bak','configuration')        os.remove('configuration.bak')        print('已经删除!')

转载地址:http://bblof.baihongyu.com/

你可能感兴趣的文章
(PAT 1154) Vertex Coloring (图的广度优先遍历)
查看>>
(PAT 1115) Counting Nodes in a BST (二叉查找树-统计指定层元素个数)
查看>>
(PAT 1143) Lowest Common Ancestor (二叉查找树的LCA)
查看>>
(PAT 1061) Dating (字符串处理)
查看>>
(PAT 1118) Birds in Forest (并查集)
查看>>
数据结构 拓扑排序
查看>>
(PAT 1040) Longest Symmetric String (DP-最长回文子串)
查看>>
(PAT 1145) Hashing - Average Search Time (哈希表冲突处理)
查看>>
(1129) Recommendation System 排序
查看>>
PAT1090 Highest Price in Supply Chain 树DFS
查看>>
(PAT 1096) Consecutive Factors (质因子分解)
查看>>
(PAT 1019) General Palindromic Number (进制转换)
查看>>
(PAT 1073) Scientific Notation (字符串模拟题)
查看>>
(PAT 1080) Graduate Admission (排序)
查看>>
Tree UVA - 548 (DFS+建立二叉树)
查看>>
Play on Words UVA - 10129 (欧拉路径)
查看>>
mininet+floodlight搭建sdn环境并创建简答topo
查看>>
(计蒜客) 取石子游戏 (gcd算法灵活运用)
查看>>
Prime Path POJ - 3126 (BFS,素数距离)
查看>>
Wireless Network POJ - 2236 (并查集)
查看>>