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