需要掌握的知识:

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之ShareSDK实现分享、第三方登录等功能

    (1)官方下载ShareSDK iOS 2.8.8,地址:http://sharesdk.cn/ (2)根据实际情况,引入相关的库,参考官方文档. (3)在项目的AppDelegate中一般情况下有三 ...

  2. textview设置drawable

    textview可以在上下左右四个方向添加图片,同时也可以动态改变这些图片:   下面有我写的一个例子: 在xml文件中:  <TextView                 android: ...

  3. log4j配置

    log4j.rootCategory=DEBUG , R, D,stdout # Console log4j.appender.stdout=org.apache.log4j.ConsoleAppen ...

  4. MySQL 使用XtraBackup的shell脚本介绍

    mysql_backup.sh是关于MySQL的一个使用XtraBackup做备份的shell脚本,实现了简单的完整备份和增量备份.以及邮件发送备份信息等功能.功能目前还比较简单,后续将继续完善和增加 ...

  5. GRANT/SELECT View时的遭遇ORA-01720和ORA-01031错误

    关于创建视图遇到ORA-01031错误信息,请参考我以前整理的一篇文章Create view failed with ORA-01031:insufficient privileges,本来以为我那篇 ...

  6. ORACLE应用调优:请避免SQL做大量循环逻辑处理

    前阵子遇到一个案例:一个同事说以前一个运行很正常的包,突然间比以前慢了很多,执行时间非常长,晚上的作业调用这个包跑了几个小时也没有跑出数据.于是我在跟踪.优化过程中定位到包中一个存储过程的一段SQL, ...

  7. Remote table-valued function calls are not allowed

    在SQL Server中,在链接服务器中调用表值函数(table-valued function)时,会遇到下面错误: SELECT * FROM LNK_TEST.TEST.DBO.TEST(12) ...

  8. Oracle表的几种连接方式

    1,排序 - - 合并连接(Sort Merge Join, SMJ) 2,嵌套循环(Nested Loops, NL) 3,哈希连接(Hash Join, HJ) Join是一种试图将两个表结合在一 ...

  9. SQL Server 2008 安装过程中遇到“性能计数器注册表配置单元一致性”检查失败 问题的解决方法

    操作步骤: 1. 在 Microsoft Windows 2003 或 Windows XP 桌面上,依次单击"开始"."运行",然后在"打开&quo ...

  10. CentOS7minimal MySql的卸载及安装

    因为CentOS7精简版默认是有残留的MySql的,所以开始时一定要先卸载掉原来的MySql 首先要使用root用户登录 卸载: 1.卸载原有程序 yum remove mysql mysql-ser ...