#!/usr/bin/env python
import os,sys,time,re,prettytable,json
from collections import defaultdict,OrderedDict
conf='haproxy.cfg' ###指定haproxy配置文件###
jgf=''
######################1.input输入字符类型转化函数#######################
def input_handle(s):
if str.isdigit(s): ###对输入是否是数字进行判断###
s = int(s) ###如果输出的是个数字,则转化为整数类型###
return s ###返回输入字符###
###########################2.backend列表展示函数############################
def backend_read(conf):
backend_list = [] ###初始化backend的列表###
show_dict = {} ###初始化要返回的显示字典###
backend_name_dict = defaultdict(list) ###定义一个value为列表的字典,用来存放server###
server_flag = False ###初始化server判断标志位###
with open(conf,'r') as ha: ###打开haproxy配置文件###
for line in ha:
server_dict = OrderedDict() ###定义一个有序字典###
line = line.strip('n')
#情况1
if re.match('backend',line): ###匹配配置文件以backend开头的行###
backend_name = re.split('s ',line)[1]
backend_list.append(backend_name) ###将配置到的backend的名称插入到列表###
server_flag = True ###赋值标志位为真,用来与server关联###
#情况2
elif server_flag and re.match('s server',line): ###匹配配置文件以server开头的行###
server_info = re.split('s ',line) ###对server进行分隔###
server_dict['name'] = server_info[2] ###对server的具体信息进行字典赋值###
server_dict['address'] = server_info[3]
server_dict['weight'] = server_info[5]
server_dict['maxconn'] = server_info[7]
backend_name_dict[backend_name].append(server_dict) ###将server字典与backend的名称进行关联###
else:
server_flag = False ###当server没匹配到,赋值标志位为假,结束关联###
for k,v in enumerate(backend_list,1):
show_dict[k] = v ###对backend名称进行新字典赋值,方便查询和展示###
print('%d . %s' % (k,v)) ###输出backend列表###
return(show_dict,backend_name_dict) ###返回显示的字典和backend-server字典###
########################3.显示server服务器函数#############################
def backend_server_show(backend_show_value,server_show_dict):
############对backend名称进行遍历并加上数字编号###########################
print(jgf.center(70,'='))
print('