2019独角兽企业重金招聘Python工程师标准>>>

配置文件模板:
defaultslog globalmode httpoption httpcloseoption dontlognulloption abortoncloseoption redispatchretries 3maxconn 20480balance roundrobintimeout connect 15000timeout client 15000timeout server 15000listen admin_statbind *:2008mode httpoption httplogstats refresh 30sstats uri /statusstats realm Haproxy\ Statisticsstats auth admin:123456stats hide-versionstats admin if TRUElisten image.eddy.com_LBbind 10.25.16.11:8000balance roundrobinoption forwardforoption originaltomode httpbalance roundrobinserver  pwepaypubc0101  pwepaypubc0101:8000 check inter 5000  weight 1server  pwepaypubc0102  pwepaypubc0102:8000 check inter 5000  weight 1listen payment.eddy.com:8080_HAbind 10.25.16.11:8080mode tcpserver  pwepaypubc0101 pwepaypubc0101:8080 check inter 5000  weight 1server  pwepaypubc0102 pwepaypubc0102:8080 check inter 5000  weight 1 backup1.查询配置文件
#!/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_HAbind 10.25.16.11:8080mode tcpserver  pwepaypubc0101 pwepaypubc0101:8080 check inter 5000  weight 1server  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   abcdbind   10.25.16.11:8002mode   httpserver 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 + 1line_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   abcdbind   10.25.16.11:8002mode   httpserver 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_lineprint line[-1]else:key_line1 = listen_line[listen_line.index(k)+1]-2print key_lineprint key_line1read = 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:abcdlisten   abcdbind   10.25.16.11:8002mode   httpserver 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   abcdbind   10.25.16.11:8002mode   httpserver 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

转载于:https://my.oschina.net/eddylinux/blog/537174

python操作haproxy配置文件实例相关推荐

  1. python操作ini配置文件

    一..ini文件说明 格式如下: ;comments [section1] Param1 = value1 Param2= value2 [section2] Param3= value3 Param ...

  2. Python操作*.cfg配置文件

    配置文件是一类系统或应用软件用于进行配置自己功能,特性的文件 扩展名为.cfg的文件是常用配置文件中的一种类型 使用python对*.cfg文件可进行读写操作,这里以读写mysql配置文件为例: 创建 ...

  3. python的cfg是什么模块_python操作cfg配置文件方式

    *.cfg文件一般是程序运行的配置文件,python为读写常见配置文件提供了一个ConfigParser模块,所以在python中解析配置文件相当简单,下面就举例说明一下具体的操作方法. 写文件代码: ...

  4. pyyaml操作yaml配置文件基于python

    在测试工作中,可以使用yaml编写测试用例,执行测试用例时直接获取yaml中的用例数据进行测试(如:接口自动化测试) 1.什么是yaml 是一种可读的数据序列化语言,通常用于配置文件 非常简洁和强大, ...

  5. python中cfg_python操作cfg配置文件方式

    *.cfg文件一般是程序运行的配置文件,python为读写常见配置文件提供了一个ConfigParser模块,所以在python中解析配置文件相当简单,下面就举例说明一下具体的操作方法. 写文件代码: ...

  6. Oracle使用ini启动,python操作ini类型配置文件的实例教程

    一.ini文件介绍 INI文件格式是某些平台或软件上的配置文件的非正式标准,以节(section)和键(key)构成,常用于微软Windows操作系统中.这种配置文件的文件扩展名多为INI 二.ini ...

  7. kafka实战教程(python操作kafka),kafka配置文件详解

    全栈工程师开发手册 (作者:栾鹏) 架构系列文章 应用往Kafka写数据的原因有很多:用户行为分析.日志存储.异步通信等.多样化的使用场景带来了多样化的需求:消息是否能丢失?是否容忍重复?消息的吞吐量 ...

  8. python处理excel表格实例-使用Python操作excel文件的实例代码

    使用的类库 pip install openpyxl 操作实现 •工作簿操作 # coding: utf-8 from openpyxl import Workbook # 创建一个excel工作簿 ...

  9. Docker selenium自动化 - 使用python操作docker,python运行、启用、停用和查询容器实例演示

    Docker selenium 自动化 - 使用 Python 操作 docker 运行.启用.停用和查询容器实例演示 第一章:Python 操作 docker ① python 运行 docker ...

最新文章

  1. libreadline.so.6: undefined symbol
  2. RS232串口交叉直连
  3. E2017E0605-hm
  4. try-catch捕获异常信息后Spring事务失效处理方法
  5. [收藏]上班族的真实写照
  6. PXE-preboot execute environment
  7. 我爱Java系列---【1.Vue的快速入门案例】
  8. 【LeetCode】【字符串】题号:*506. 相对名次
  9. H5 FormData 表单数据对象详解 与 Json 对象相互转换
  10. 32bit程序在64bit操作系统下处理重定向细节
  11. 手机图片怎么免费转换成PDF格式?教程来了
  12. 2:算法php/go [二分查找 ;二叉树的层序遍历 ;最长无重复子数组]
  13. 代码检查工具--findBugs
  14. 电路方案分析(十三)采用 CAN 的汽车分立式 SBC 预升压、后降压参考设计方案
  15. 【OMNeT++】ALOHA协议仿真中的channelUtilization
  16. Elasticsearch 7.7.0 高阶篇-聚合技术
  17. 安利超实用的(cc协议)游戏3d模型素材网站
  18. Python中的对日期时间的处理
  19. 新工科数学基础 系列书籍
  20. 函数笔记(常数函数、幂函数、指数函数、对数函数、三角函数、反三角函数、复合函数)

热门文章

  1. python raise
  2. C/C++:Windows编程—Hook IE浏览器实现URL拦截及更改(下)
  3. Go语言编程—Go语言中JSON的处理(map、struct 和 JSON字符串的相互转换)
  4. WPF中制作立体效果的文字或LOGO图形
  5. P1955 [NOI2015]程序自动分析 离散化学习 lower_bound学习
  6. PHP初入--表单元素
  7. 人人都可以创造自己的AI:深度学习的6大应用及3大成熟领域
  8. 入门干货:Python操作Word文件经验分享
  9. 怎么让电脑屏幕一直亮着_电脑屏幕总是闪烁?试试这个方法
  10. 代码规范 设计模式落地之路