需要掌握的知识:

1、函数

2、文件处理

3、tag的用法

4、程序的解耦

需求:

1:查询
2:添加
3:删除
4:修改
5:退出

haproxy.conf 配置文件内容:

 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.org
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.oldboy1.org
server 10.10.0.10 10.10.0.10 weight 9999 maxconn 33333333333
server 10.10.10.1 10.10.10.1 weight 22 maxconn 2000
server 2.2.2.4 2.2.2.4 weight 20 maxconn 3000
backend www.oldboy2.org
server 3.3.3.3 3.3.3.3 weight 20 maxconn 3000
backend www.oldboy20.org
server 10.10.0.10 10.10.0.10 weight 9999 maxconn 33333333333

一、优化后的代码:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige import os
def file_handle(filename,backend_data,record_list=None,type='fetch'): #type:fetch append change
new_file=filename+'_new'
bak_file=filename+'_bak'
if type == 'fetch':
r_list = []
with open(filename, 'r') as f:
tag = False
for line in f:
if line.strip() == backend_data:
tag = True
continue
if tag and line.startswith('backend'):
break
if tag and line:
r_list.append(line.strip())
for line in r_list:
print(line)
return r_list
elif type == 'append':
with open(filename, 'r') as read_file, \
open(new_file, 'w') as write_file:
for r_line in read_file:
write_file.write(r_line) for new_line in record_list:
if new_line.startswith('backend'):
write_file.write(new_line + '\n')
else:
write_file.write("%s%s\n" % (' ' * 8, new_line))
os.rename(filename, bak_file)
os.rename(new_file, filename)
os.remove(bak_file)
elif type == 'change':
with open(filename, 'r') as read_file, \
open(new_file, 'w') as write_file:
tag=False
has_write=False
for r_line in read_file:
if r_line.strip() == backend_data:
tag=True
continue
if tag and r_line.startswith('backend'):
tag=False
if not tag:
write_file.write(r_line)
else:
if not has_write:
for new_line in record_list:
if new_line.startswith('backend'):
write_file.write(new_line+'\n')
else:
write_file.write('%s%s\n' %(' '*8,new_line))
has_write=True
os.rename(filename, bak_file)
os.rename(new_file, filename)
os.remove(bak_file) def fetch(data):
backend_data="backend %s" %data
return file_handle('haproxy.conf',backend_data,type='fetch') def add(data):
backend=data['backend']
record_list=fetch(backend)
current_record="server %s %s weight %s maxconn %s" %(data['record']['server'],\
data['record']['server'],\
data['record']['weight'],\
data['record']['maxconn'])
backend_data="backend %s" %backend if not record_list:
record_list.append(backend_data)
record_list.append(current_record)
file_handle('haproxy.conf',backend_data,record_list,type='append')
else:
record_list.insert(0,backend_data)
if current_record not in record_list:
record_list.append(current_record)
file_handle('haproxy.conf',backend_data,record_list,type='change') def remove(data):
backend=data['backend']
record_list=fetch(backend)
current_record="server %s %s weight %s maxconn %s" %(data['record']['server'],\
data['record']['server'],\
data['record']['weight'],\
data['record']['maxconn'])
backend_data = "backend %s" % backend
if not record_list or current_record not in record_list:
print('\033[33;1m无此条记录\033[0m')
return
else:
if len(record_list) == 1: #判断record_list是否还有一条记录
record_list.remove(current_record) #如果只剩一条记录,就把最后一条记录和backend都删除掉
else:
record_list.insert(0,backend_data)
record_list.remove(current_record)
file_handle('haproxy.conf',backend_data,record_list,type='change') #{'backend':'www.oldboy20.org','record':{'server':'10.10.0.10','weight':9999,'maxconn':33333333333}} def change(data):
backend=data[0]['backend']
record_list=fetch(backend) old_record="server %s %s weight %s maxconn %s" %(data[0]['record']['server'],\
data[0]['record']['server'],\
data[0]['record']['weight'],\
data[0]['record']['maxconn']) new_record = "server %s %s weight %s maxconn %s" % (data[1]['record']['server'], \
data[1]['record']['server'], \
data[1]['record']['weight'], \
data[1]['record']['maxconn'])
backend_data="backend %s" %backend if not record_list or old_record not in record_list:
print('\033[33;1m无此内容\033[0m')
return
else:
record_list.insert(0,backend_data)
index=record_list.index(old_record)
record_list[index]=new_record
file_handle('haproxy.conf',backend_data,record_list,type='change') if __name__ == '__main__':
msg='''
1:查询
2:添加
3:删除
4:修改
5:退出
'''
menu_dic={
'':fetch,
'':add,
'':remove,
'':change,
'':exit,
}
while True:
print(msg)
choice=input("操作>>: ").strip()
if len(choice) == 0 or choice not in menu_dic:continue
if choice == '':break data=input("数据>>: ").strip() #menu_dic[choice](data)==fetch(data)
if choice != '':
data=eval(data)
menu_dic[choice](data) #add(data) # [{'backend':'www.oldboy20.org','record':{'server':'2.2.2.3','weight':20,'maxconn':3000}},{'backend':'www.oldboy10.org','record':{'server':'10.10.0.10','weight':9999,'maxconn':33333333333}}]

二、分解实现上面过程:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige import os #def file_handle(filename,backend_data,record_list=None,type='fetch'): #实现查询功能 def fetch(data):
backend_data="backend %s" %data #backend www.oldboy1.org 查找匹配到这行,找到对应的server记录,用字符串拼接的方法
record_list=[] #定义一个空列表
with open('haproxy.conf','r') as f: #打开haproxy.conf配置文件
tag=False #报警器不响
for line in f: #去查找文件
if line.strip() == backend_data: #把文件的每一行\n去掉,才能进行比较,就找到这行backend www.oldboy1.org
tag=True #找到人就响警报
continue #就跳出这个循环
if tag and line.startswith('backend'): #找到下一行的backend,backend www.oldboy2.org 我们就跳出循环
break
if tag and line: #相当于警报响了
record_list.append(line.strip()) #找到了server 10.10.0.10 10.10.0.10 weight 9999 maxconn 33333333333,就要把他加到列表中
for line in record_list:
print(line) #给用户打印找到的信息
return record_list #给用户返回处理的信息 def add(data): backend=data['backend']
record_list=fetch(backend)
current_record = "server %s %s weight %s maxconn %s" % (data['record']['server'], \
data['record']['server'], \
data['record']['weight'], \
data['record']['maxconn'])
backend_data = "backend %s" % backend if not record_list:
record_list.append(backend_data)
record_list.append(current_record)
with open('haproxy.conf','r') as read_file,\
open('haproxy_new.conf','w') as write_file:
for r_line in read_file:
write_file.write(r_line) for new_line in record_list:
if new_line.startswith('backend'):
write_file.write(new_line+'\n')
else:
write_file.write("%s%s\n" %(' '*8,new_line)) else:
#处理recard_list
record_list.insert(0,backend_data)
record_list.append(current_record)
with open('haproxy.conf','r') as read_file, \
open('haproxy_new.conf','w') as write_file:
tag = False
has_write = False
for r_line in read_file:
if r_line.strip() == backend_data:
tag = True
continue
if tag and r_line.startswith('backend'):
tag = False
if not tag:
write_file.write(r_line)
else:
if not has_write:
for new_line in record_list:
if new_line.startswith('backend'):
write_file.write(new_line + '\n')
else:
write_file.write("%s%s\n" % (' ' * 8, new_line))
has_write = True
os.rename('haproxy.conf','haproxy_bak.conf')
os.rename('haproxy_new.conf','haproxy.conf')
os.remove('haproxy_bak.conf') #{'backend':'lhf.oldboy.org','record':{'server':'1.1.1.1','weight':2,'maxconn':200}} def remove(data): backend=data['backend']
record_list=fetch(backend)
current_record = "server %s %s weight %s maxconn %s" % (data['record']['server'], \
data['record']['server'], \
data['record']['weight'], \
data['record']['maxconn'])
backend_data = "backend %s" % backend
if not record_list and current_record not in record_list:
print('\033[33:[1m无此条记录\033[0]')
return
else:
#处理recard_list
record_list.insert(0,backend_data)
record_list.remove(current_record)
with open('haproxy.conf','r') as read_file, \
open('haproxy_new.conf','w') as write_file:
tag = False
has_write = False
for r_line in read_file:
if r_line.strip() == backend_data:
tag = True
continue
if tag and r_line.startswith('backend'):
tag = False
if not tag:
write_file.write(r_line)
else:
if not has_write:
for new_line in record_list:
if new_line.startswith('backend'):
write_file.write(new_line + '\n')
else:
write_file.write("%s%s\n" % (' ' * 8, new_line))
has_write = True
os.rename('haproxy.conf','haproxy_bak.conf')
os.rename('haproxy_new.conf','haproxy.conf')
os.remove('haproxy_bak.conf') #{'backend':'www.oldboy1.org11111','record':{'server':'11.100.200.1','weight':22,'maxconn':200}} def change(data):
backend=data[0]['backend'] #找到要修改的第一条记录
record_list=fetch(backend)
old_record = "server %s %s weight %s maxconn %s" % (data[0]['record']['server'], \
data[0]['record']['server'], \
data[0]['record']['weight'], \
data[0]['record']['maxconn']) new_record = "server %s %s weight %s maxconn %s" % (data[1]['record']['server'], \
data[1]['record']['server'], \
data[1]['record']['weight'], \
data[1]['record']['maxconn'])
backend_data = "backend %s" % backend
if not record_list and old_record not in record_list: #判断这个文件在原文件中不存在
print('\033[33:[1m无此内容\033[0]')
return
else:
record_list.insert(0,backend_data) #判断文件存在原文件中
index=record_list.index(old_record) #求出这个索引
record_list[index]=new_record #用新的记录,替换掉旧记录
with open('haproxy.conf','r') as read_file, \
open('haproxy_new.conf','w') as write_file:
tag = False
has_write = False
for r_line in read_file:
if r_line.strip() == backend_data:
tag = True
continue
if tag and r_line.startswith('backend'):
tag = False
if not tag:
write_file.write(r_line)
else:
if not has_write:
for new_line in record_list:
if new_line.startswith('backend'):
write_file.write(new_line + '\n')
else:
write_file.write("%s%s\n" % (' ' * 8, new_line))
has_write = True
os.rename('haproxy.conf','haproxy_bak.conf')
os.rename('haproxy_new.conf','haproxy.conf')
os.remove('haproxy_bak.conf') #backend www.oldboy2.org
#server 3.3.3.3 3.3.3.3 weight 20 maxconn 3000
#[{'backend':'www.oldboy2.org','record':{'server':'3.3.3.3','weight':20,'maxconn':3000}},{'backend':'www.oldboy2.org','record':{'server':'10.10.10.10','weight':30,'maxconn':3000000}}] def exit(data):
pass if __name__ == '__main__': #__name__是python的内置变量,他会把__name__赋值给__main__
msg='''
1:查询
2:添加
3:删除
4: 修改
5:退出
'''
# 定义一个字典,key对应fetch函数,其它也相同
menu_dic={
'':fetch,
'':add,
'':remove,
'':change,
'':exit,
}
while True: #死循环,不断跟用户交互
print(msg) #打印出msg信息,让用户选择菜单
choice=input("操作>>: ").strip() #去掉空格
if len(choice) == 0 or choice not in menu_dic:continue #len(choice)==0,判断他是不是空,choice不在字典里,就跳出这个操作
if choice == '':break data=input("数据>>: ").strip() #用户输入的是字符串 #menu_dic[choice](data)==fetch(data)
if choice != '': #如果输入的不是查询的话,就需要把字符串转换成字典
data=eval(data) #因为添加和删除都要求是字典的形式,所以我们要把用户输入的字符串转成字典的形式
menu_dic[choice](data) #add(data)

python基础-修改haproxy配置文件的更多相关文章

  1. python基础修改haproxy配置文件

    1.通过eval(),可以将字符串转为字典类型. 2.Encode过程,是把python对象转换成json对象的一个过程,常用的两个函数是dumps和dump函数.两个函数的唯一区别就是dump把py ...

  2. python编辑修改haproxy配置文件--文件基础操作

    一.需求分析 有查询,删除,添加的功能 查询功能:查询则打印查询内容,如果不存在也要打印相应的信息 删除功能:查询到要删除内容则删除,打印信息. 添加功能:同上. 二.流程图 三.代码实现 本程序主要 ...

  3. s12-day03-work01 python修改haproxy配置文件(初级版本)

    #!/usr/local/env python3 ''' Author:@南非波波 Blog:http://www.cnblogs.com/songqingbo/ E-mail:qingbo.song ...

  4. Python3.5 day3作业二:修改haproxy配置文件。

    需求: 1.使python具体增删查的功能. haproxy的配置文件. global log 127.0.0.1 local2 daemon maxconn 256 log 127.0.0.1 lo ...

  5. python基础-4.1 open 打开文件练习:修改haproxy配置文件

    1.如何在线上环境优雅的修改配置文件? 配置文件名称ini global log 127.0.0.1 local2 daemon maxconn 256 log 127.0.0.1 local2 in ...

  6. 用python修改haproxy配置文件

    需求: 当用户输入域名的时候,显示出来下面的记录 当用户需要输入添加纪录的时候,添加到你需要的那个域名下面 global log 127.0.0.1 local2 daemon maxconn 256 ...

  7. Python小程序之动态修改Haproxy配置文件

    需求如下: 1.动态的查询添加删除haproxy节点信息 2.程序功能:add(添加).Del(删除).Query(查询) 3.添加时实例字符串为:  {'backend': 'www.oldboy. ...

  8. python作业:HAproxy配置文件操作(第三周)

    一.作业需求: 1. 根据用户输入输出对应的backend下的server信息 2. 可添加backend 和sever信息 3. 可修改backend 和sever信息 4. 可删除backend ...

  9. Python3学习之路~2.10 修改haproxy配置文件

    需求: .查 输入:www.oldboy.org 获取当前backend下的所有记录 .新建 输入: arg = { 'bakend': 'www.oldboy.org', 'record':{ 's ...

随机推荐

  1. iOS 域名解析

    如何在iOS下进行域名的解析? /** *  域名解析ip * *  @param hostName 域名 * *  @return ip */ +(NSString *) getIPWithHost ...

  2. sqlserver下调试sql语句

    现在版本的sqlServer已经支持调试功能了,但是在使用的时候用到的却很少(毕竟print习惯了..) 这里做一个笔记,简单的说明一下在sqlserver下调试的方法: declare @i int ...

  3. Thinking in Java 笔记

    大二就买了这本书,如今再看这本书,看到了一些以前没看的细节,也有了不同的体会.本文使用第4版,整理每章的笔记心得.老外的书有个特点,他会花费大量的文字去阐述一个概念,这比堆代码强多了. 第 1 章 对 ...

  4. jQuery操作select控件取值和设值

    1.级联select的操作,后一个select的值随着前一个select选中值变化 $(".select_A").change(function(){ $(".selec ...

  5. jar命令的用法详解

    本文详细讲述了JAR命令的用法,对于大家学习和总结jar命令的使用有一定的帮助作用.具体如下: JAR包是Java中所特有一种压缩文档,其实大家就可以把它理解为.zip包.当然也是有区别的,JAR包中 ...

  6. Python进阶【第一篇】socket

    1.socket模块 要使用socket.socket()函数来创建套接字.其语法如下: socket.socket(socket_family,socket_type,protocol=0) soc ...

  7. DMZ区

    DMZ是英文“Demilitarized Zone”的缩写,它是为了解决安装防火墙后外部网络不能访问内部网络服务器的问题,而设立的一个非安全系统与安全系统之间的缓冲区,这个缓冲区位于企业内部网络和外部 ...

  8. C# 自定义文件图标 双击启动 (修改注册表)

    程序生成的自定义文件,比如后缀是.test 这种文件怎么直接启动打开程序,并打开本文件呢 1.双击打开 2.自定义的文件,有图标显示 3.自定义的文件,点击右键有相应的属性 后台代码:(如何在注册表中 ...

  9. linux 命令行中常用光标移动快捷键

    对linux不怎么熟悉,以前在linux中敲命令的时候,要移动光标,傻傻的一个一个的移动,感觉特不爽.有几个常用的快捷键. ctrl+左右键:在单词之间跳转 ctrl+a:跳到本行的行首 ctrl+e ...

  10. OpenStack云计算快速入门之二:OpenStack安装与配置

    原文:http://blog.chinaunix.net/uid-22414998-id-3265685.html OpenStack云计算----快速入门(2) 该教程基于Ubuntu12.04版, ...