需求
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
}
}

操作haproxy.cfg的haproxy.py文件

#!/usr/bin/evn python
#-*- coding=utf-8 -*-
import json
import os # 根据backend名字查找backend信息
def fetch(backend_name):
line_list = []
flag = False
with open('D:/python/day03/haproxy.cfg','r') as ha:
for line in ha:
if line.startswith("backend %s" % backend_name):
flag = True
continue
if flag and line.strip().startswith('server'):
line_list.append(line.strip())
if line.startswith('backend'):
# flag = False
break return line_list # 添加backend信息
def add(info_dict):
current_title = info_dict['backend']
current_list = 'server %s %s weight %d maxconn %d' % (info_dict['record']['server'],info_dict['record']['server'],info_dict['record']['weight'],info_dict['record']['maxconn'])
fetch_list = fetch(current_title)
# backend是否存在
if fetch_list:
if current_list in fetch_list:
pass
else:
fetch_list.append(current_list)
# 如果根据backend找到了这个backend说明有记录,继续添加server即可 flag = False
has_write = False
with open('haproxy.cfg') as read_obj,open('haproxy.new','w') as write_obj:
for read_line in read_obj:
# 将haproxy.cfg分为上、中、下三部分
# fetch_list为中间部分 # 读取配置文件,写信配置文件
# 读上-->写上
# 将处理完的配置文件fetch_list写入新的配置文件中
# 读下-->写下
if read_line.strip() == 'backend %s' % current_title:
write_obj.write(read_line)
flag = True
continue
if flag and read_line.startswith('backend'):
flag = False
if flag:
for i in fetch_list:
if not has_write:
write_obj.write('%s%s\n' % (' '*8,i))
has_write = True
else:
write_obj.write(read_line)
else:
# 没有这条记录需要添加backend和server
with open('haproxy.cfg') as read_obj,open('haproxy.new','w') as write_obj:
for read_line in read_obj:
write_obj.write(read_line)
write_obj.write('backend %s\n' % current_title)
write_obj.write(' '*8 + current_list)
# 先将haproxy.cfg备份为haproxy.cfg.bak,将新的文件替换为haproxy.cfg
os.rename('haproxy.cfg','haproxy.cfg.bak')
os.rename('haproxy.new','haproxy.cfg') # 删除backend信息函数
def del_backend(info_dict):
current_title = info_dict.get('backend')
fetch_list = fetch(current_title) current_record = 'server %s %s weight %d maxconn %d' % (info_dict['record']['server'],info_dict['record']['server'],info_dict['record']['weight'],info_dict['record']['maxconn']) # 判断是否有这条记录
if fetch_list:
if current_record in fetch_list:
# 将该记录删掉
fetch_list.remove(current_record)
print fetch_list
with open('haproxy.cfg') as read_obj,open('haproxy.new','w') as write_obj:
flag = False
has_write = False
for read_line in read_obj: if read_line.strip() == 'backend %s' % current_title:
write_obj.write(read_line)
flag = True
continue
if flag and read_line.startswith('backend'):
flag = False
if flag:
if not has_write:
for line in fetch_list:
write_obj.write('%s%s\n' % (' '*8,line))
has_write = True
else:
write_obj.write(read_line)
else:
print('no this server record') if os.path.exists('D:/python/day03/haproxy.new'):
os.rename('haproxy.cfg','haproxy.cfg.bak')
os.rename('haproxy.new','haproxy.cfg')
else:
print('no this record') # 需要添加的记录
data = '{"backend": "www.oldboy.org","record":{"server": "100.1.7.168","weight": 20,"maxconn": 30}}'
# 转换为json格式
info_dict = json.loads(data) input_num = raw_input('please input your select : ')
if str.isdigit(input_num):
input_num = int(input_num)
# 1.查找记录 2.增加记录 3.删除记录
if input_num == 1:
pass
elif input_num == 2:
add(info_dict)
elif input_num == 3:
del_backend(info_dict)

haproxy.cfg配置文件

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
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
server 100.1.7.10 100.1.7.10 weight 10 maxconn 2000
backend mysqlserver
server mysql1 10.1.1.110:3306 weight 20 maxconn 300
server mysql2 10.1.1.120:3306 weight 10 maxconn 200
frontend mysql
bind *:3306
mode tcp
log global
default_backend mysqlserver

python操作haproxy.cfg文件的更多相关文章

  1. Python 操作 MS Excel 文件

    利用 Python 对 Excel 文件进行操作需要使用第三方库: openpyxl,可执行 pip install openpyxl 进行安装 1. 导入 openpyxl 模块 导入 openpy ...

  2. python操作excel表格文件--使用xlrd模块

    原文: http://www.cnblogs.com/lhj588/archive/2012/01/06/2314181.html 引言: 实际工作中,可能很多情况下都会用到excel表格,像如果不需 ...

  3. python操作上级子文件

    . └── folder ├── data │ └── data.txt └── test1 └── test2 └── test.py import os '***获取当前目录***'print o ...

  4. 第三章:Python基础の函数和文件操作实战

    本課主題 Set 集合和操作实战 函数介紹和操作实战 参数的深入介绍和操作实战 format 函数操作实战 lambda 表达式介绍 文件操作函数介紹和操作实战 本周作业 Set 集合和操作实战 Se ...

  5. 关于Haproxy安装和配置:负载配置【haproxy.cfg】问题记录

    1.  存放地址: more /etc/haproxy/haproxy.cfg ps -ef | grep haproxy 看看有没有haproxy的进程就是了 或者看看服务器的23306的端口有没有 ...

  6. python操作文件练习,配置haproxy

    在使用python操作文件的时候,特别是对于网络设备,通常操作配置文件,会简化配置量,配置文件加载到内存中,运行时使用的是内存中的配置,内存中配置修改后立即生效,如果不将配置内容保存到硬盘中,则下次重 ...

  7. python之haproxy配置文件操作(第三天)

    作业: 对haproxy配置文件进行操作 要求: 对haproxy配置文件中backend下的server实现增删改查的功能 一.这个程序有二个版本 1. python2.7版本见haproxy_py ...

  8. Python基础7:文件操作

    [ 文件操作] 1 对文件操作流程 打开文件,得到文件句柄并赋值给一个变量 通过句柄对文件进行操作 关闭文件 现有文件如下: 昨夜寒蛩不住鸣. 惊回千里梦,已三更. 起来独自绕阶行. 人悄悄,帘外月胧 ...

  9. Python 第三天 文件操作(2)

    文件操作 操作文件时,一般需要经历如下步骤: 打开文件 操作文件 一.打开 文件句柄 = file('文件路径', '模式') 注:python中打开文件有两种方式,即:open(...) 和  fi ...

随机推荐

  1. 迅雷thunder://协议解密

    echo -n 'thunder://''Cg==' | sed 's?thunder://??' | base64 -d | sed 's/^AA//; s/ZZ$//' 将thunder://替换 ...

  2. 【bzoj3680】平衡点 模拟退火

    模拟退火是一种求函数最值问题的随机算法. 给定一个函数的某一初始坐标,可以拟定一个"温度"(这里主要是借用退火的物理意义),这里的温度可以理解成自变量可以取值的范围.之后在当前最优 ...

  3. jdk8的特性stream().map()

    转: https://blog.csdn.net/sanchan/article/details/70753645 java8的optional的使用: http://www.jdon.com/ide ...

  4. idea中gitlab新创建分支查找不到的原因

    问题: 很多人说是这样解决: https://blog.csdn.net/rodulf/article/details/51536532 然后对于我来说没用............ 这里先说下如何从m ...

  5. HTTP Status 405 - HTTP method POST is not supported by this URL

    出现这个问题, 1.在servlet中没有调用post()方法引起的 2.在serlvet中跳转没有用外跳(response.sendRedirect()) 我的是因为第一种,是没有写dopost() ...

  6. python---RabbitMQ(3)exchange中关键字发送direct(组播)

    设置关键字,交换机根据消费者传递的关键字判断是否与生产者的一致,一致则将数据传递给消费者 可以实现对消息分组 生产者: # coding:utf8 # __author: Administrator ...

  7. Spark记录-大数据简介

    什么是大数据 大数据(big data),指无法在一定时间范围内用常规软件工具进行捕捉.管理和处理的数据集合,是需要新处理模式才能具有更强的决策力.洞察发现力和流程优化能力的海量.高增长率和多样化的信 ...

  8. CM记录-操作系统调优

    1.避免使用swap分区---将hadoop守护进程的数据交换到磁盘的行为可能会导致操作超时:物理内存(交换)--Swap分区 2.调整内存分配策略---操作系统内核根据vm.overcommit_m ...

  9. Java编程思想 学习笔记12

    十二.通过异常处理错误  Java的基本理念是“结构不佳的代码不能运行”. Java中的异常处理的目的在于通过使用少于目前数量的代码来简化大型.可靠的程序的生成,并且通过这种方式可以使你更加自信:你的 ...

  10. Solr之java操作

    参考教程: http://www.cnblogs.com/xia520pi/p/3625232.html http://www.cnblogs.com/hujunzheng/p/5647896.htm ...