配置文件模板: defaults log global mode http option httpclose option dontlognull option abortonclose option redispatch retries 3 maxconn 20480 balance roundrobin timeout connect 15000 timeout client 15000 timeout server 15000 listen admin_stat bind *:2008 mode http option httplog stats refresh 30s stats uri /status stats realm Haproxy\ Statistics stats auth admin:123456 stats hide-version stats admin if TRUE listen image.eddy.com_LB bind 10.25.16.11:8000 balance roundrobin option forwardfor option originalto mode http balance roundrobin server pwepaypubc0101 pwepaypubc0101:8000 check inter 5000 weight 1 server pwepaypubc0102 pwepaypubc0102:8000 check inter 5000 weight 1 listen payment.eddy.com:8080_HA bind 10.25.16.11:8080 mode tcp server pwepaypubc0101 pwepaypubc0101:8080 check inter 5000 weight 1 server pwepaypubc0102 pwepaypubc0102:8080 check inter 5000 weight 1 backup 1.查询配置文件 #!/usr/bin/env python # encoding: utf-8 import json import re import linecache import time import shutil #定义listen行号列表 listen_line = [] #定义文件行号列表 line = [] #定义文件内容列表 line_content = [] #定义listen行号与listen那一行内容字典 listen_dic = {} def query_cfg(key): #打开文件 with open('haproxy.cfg','r') as obj: #循环文件行号与行内容 for (num,value) in enumerate(obj): #添加行号列表 line.append(num) line_content.append(value) #匹配以listen开头的行 if re.match('(listen.*?)',value,re.S): #添加listen的行号 listen_line.append(num) #让行内容之间的空格用‘_’替换 value = str(value).replace(' ','_') #添加listen行号和所在行号内容 listen_dic.setdefault(num,value) #遍历listen行号与内容的字典 for k,v in listen_dic.items(): #匹配以listen开头中间任意字符以关键字结尾的 if re.match('(listen.*?%s)' %(key),v,re.S): #定义关键字所在listen行号 key_line = listen_line.index(k) #判断关键字listen行号是否是最后一个listen行号 if key_line+1 == len(listen_line): #打印listen关键字行号到最后一行的内容 for i in range(listen_line[key_line],line[-1]+2): linecache.updatecache('haproxy.cfg') print linecache.getline('haproxy.cfg',i), else: #判断关键listen行号不是最后一个listen就打印两个listen行号之间的内容 for i in range(listen_line[key_line],listen_line[key_line+1]): linecache.updatecache('haproxy.cfg') print linecache.getline('haproxy.cfg',i), query_cfg('payment.eddy.com:8080_HA') Connected to pydev debugger (build 135.1057) listen payment.eddy.com:8080_HA bind 10.25.16.11:8080 mode tcp server pwepaypubc0101 pwepaypubc0101:8080 check inter 5000 weight 1 server pwepaypubc0102 pwepaypubc0102:8080 check inter 5000 weight 1 backup #2.为配置文件添加节点 def add_cfg(): read = raw_input("please input listen:") result = exist_cfg(read) if result: print 'please choose another listen name' else: content = raw_input('please input listen content:') #格式化输入内容 content_dict = json.loads(content) listen_title = '\n' + 'listen' + ' ' + content_dict['listen'] record = content_dict['record'] listen_bind = '\n' + ' ' + 'bind' + ' ' + record['bind'] listen_mode = '\n' + ' ' + 'mode' + ' ' + record['mode'] result1 = exist_cfg(content_dict['listen']) if result1: print 'please choose another listen name' else: #备份原配置文件 shutil.copyfile('haproxy.cfg','haproxy_version_%s.cfg' %time.strftime('%Y%m%d%H%M')) with open('haproxy.cfg','a') as obj: obj.writelines(listen_title) obj.writelines(listen_bind) obj.writelines(listen_mode) obj.writelines('\n server %s check inter %s weight %s maxconn %s \n' %(record['server'],record['check inter'],record['weight'],record['maxconn'])) print 'add successfull' add_cfg() Connected to pydev debugger (build 135.1057) please input listen:abcd listen is not exits please input listen content:{"listen":"abcd","record":{"bind":"10.25.16.11:8002","mode":"http","server":"pwpaystoc0102 10.25.19.52:8002","check inter":"5000","weight":"1","maxconn":"1000"}} listen is not exits add successfull 配置文件添加以下内容 listen abcd bind 10.25.16.11:8002 mode http server pwpaystoc0102 10.25.19.52:8002 check inter 5000 weight 1 maxconn 1000 #3.为配置更新 def update_cfg1(): line_content = [] listen_list = [] line = [] with open('haproxy.cfg','r') as obj: for (num,value) in enumerate(obj): line_content.append(value) line.append(num) if re.match('(listen.*?)',value,re.S): listen_list.append(num) # content = '{"listen":"abcd","record":{"server":"pwpaystoc0102 10.25.19.52:8002","check inter":"5000","weight":"1","maxconn":"1000"}}' content =raw_input('please update site:') content_dict = json.loads(content) listen_title = content_dict['listen'] record = content_dict['record'] input_content = ' server %s check inter %s weight %s maxconn %s \n' %(record['server'],record['check inter'],record['weight'],record['maxconn']) for i in line_content: if re.match('(listen.*?%s)' %(listen_title),i,re.S): if line_content.index(i) == listen_list[-1]: line_content.insert(line[-1]+1,input_content) s = ''.join(line_content) shutil.copyfile('haproxy.cfg','haproxy_version_%s.cfg' %time.strftime('%Y%m%d%H%M')) with open('haproxy.cfg','w') as obj: obj.write(s) else: current_listen_index = listen_list.index(line_content.index(i)) next_listen_index = current_listen_index + 1 line_content.insert(listen_list[next_listen_index]-1,input_content) s = ''.join(line_content) shutil.copyfile('haproxy.cfg','haproxy_version_%s.cfg' %time.strftime('%Y%m%d%H%M')) with open('haproxy.cfg','w') as obj: obj.write(s) update_cfg1() Connected to pydev debugger (build 135.1057) please update site:{"listen":"abcd","record":{"server":"pwpaystoc0102 10.25.19.52:8002","check inter":"5000","weight":"1","maxconn":"1000"}} 配置文件更新如下 listen abcd bind 10.25.16.11:8002 mode http server pwpaystoc0102 10.25.19.52:8002 check inter 5000 weight 1 maxconn 1000 server pwpaystoc0102 10.25.19.52:8002 check inter 5000 weight 1 maxconn 1000 server pwpaystoc0102 10.25.19.52:8002 check inter 5000 weight 1 maxconn 1000 #4.删除配置文件的配置 def delete_cfg(): read = raw_input("please input listen:") result = exist_cfg(read) if result: for k,v in listen_dic.items(): if re.match('(listen.*?%s)' %(read),v,re.S): key_line = listen_line[listen_line.index(k)] if key_line == listen_line[-1]: print key_line print line[-1] else: key_line1 = listen_line[listen_line.index(k)+1]-2 print key_line print key_line1 read = raw_input("please input delete line number:") del line_content[int(read)] shutil.copyfile('haproxy.cfg','haproxy_version_%s.cfg' %time.strftime('%Y%m%d%H%M')) with open('haproxy.cfg','w') as obj: new_realserver = ''.join(line_content) obj.write(new_realserver) Connected to pydev debugger (build 135.1057) please input listen:abcd listen abcd bind 10.25.16.11:8002 mode http server pwpaystoc0102 10.25.19.52:8002 check inter 5000 weight 1 maxconn 1000 server pwpaystoc0102 10.25.19.52:8002 check inter 5000 weight 1 maxconn 1000 listen is exits 97 101 please input delete line number:101 配置文件如下: listen abcd bind 10.25.16.11:8002 mode http server pwpaystoc0102 10.25.19.52:8002 check inter 5000 weight 1 maxconn 1000 注意: 1.以上输入内容必须为以下格式 {"listen":"fastdfs_group2_8002_external","record":{"bind":"10.25.16.11:8002","mode":"http","server":"pwpaystoc0102 10.25.19.52:8002","check inter":"5000","weight":"1","maxconn":"1000"}} 因为raw_input输入的内容都为字符串,需要json化 2.注意写入内容的空格与换行符 3.扩展1:你可以使用flask或django做成网页管理haproxy配置文件的方式; 4.扩展2:你可以使用while True的死循环方式把几个函数连接起来做成一个终端操作的小工具,以下代码是否可用,没有验证过,只是举例 # while True: # print ''' # =================================================== # 1.)select haproxy configuration # 2.)add haproxy listen # 3).update haproxy # 4.)delete haproxy realserver # =================================================== # ''' # read = raw_input('please choose number:') # if read == '1': # site = raw_input('please input listen:') # exist_cfg(site) # elif read == '2': # add_cfg() # elif read == '3': # update_cfg() # elif read == '4': # delete_cfg() # elif read == 'q' or read == 'quit': # break