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