需要掌握的知识:

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. Atitit. 查找linux 项目源码位置

    Atitit. 查找linux 项目源码位置 1. netstat   -anp |grep 801 1.1. 1.3 启动关闭nginx3 1.2. 找到nginx配置文件4 1.3. ./etc/ ...

  2. android四大组件(简单总结)

    activity 一个Activity通常就是一个单独的屏幕(窗口) Activity之间通过Intent进行通信 android应用中每一个Activity都必须要在AndroidManifest. ...

  3. python之ATM

    每次做一点就发出来,大神不要嫌重复 2016/11/4 今天来搞ATM,反正逃不了的,说来惭愧,这个作业是我10/4号20天前拿到的,当时是万脸蒙比的,今天又做了一点,现在算是百脸蒙比吧. 一.需求: ...

  4. web.xml 中的listener、 filter、servlet 加载顺序及其详解

    在项目中总会遇到一些关于加载的优先级问题,近期也同样遇到过类似的,所以自己查找资料总结了下,下面有些是转载其他人的,毕竟人家写的不错,自己也就不重复造轮子了,只是略加点了自己的修饰. 首先可以肯定的是 ...

  5. JAVA中的Fork/Join框架

    看了下Java Tutorials中的fork/join章节,整理下. 什么是fork/join框架 fork/join框架是ExecutorService接口的一个实现,可以帮助开发人员充分利用多核 ...

  6. 如何自动化一键部署PHP项目

    1.技能需求 完成自动化一键部署PHP需要:PHP(略懂),Shell(略懂),git(略懂) 2.最终效果 输入密码,回车,5~20秒后(一般一天一次持续交付,部署的代码量和sql脚本都不会很大) ...

  7. Linux下解压超过4G的zip文件

    从Windows平台通过FTP上传一个大小约为6G的zip文件到Linux系统(Oracle Linux Server release 5.7)上,解压过程中出现如下错误: 1: [root@gsp ...

  8. WPF 显示文件列表中使用 ListBox 变到ListView 最后使用DataGrid

    WPF 显示文件列表中使用 ListBox 变到ListView 最后使用DataGrid 故事背景: 需要检索某目录下文件,并列出来,提供选择和其他功能. 第一版需求: 列出文件供选择即可,代码如下 ...

  9. WebAPi的可视化输出模式(RabbitMQ、消息补偿相关)——所有webapi似乎都缺失的一个功能

    最近的工作我在做一个有关于消息发送和接受封装工作.大概流程是这样的,消息中间件是采用rabbitmq,为了保证消息的绝对无丢失,我们需要在发送和接受前对消息进行DB落地.在发送前我会先进行DB的插入, ...

  10. springMVC 拦截器如何做登录检查及页面跳转

    一个非常简单的登录权限拦截器 问题一:登录页面的提交请求肯定是要过滤掉的,目前采用在xml里配置<mvc:mapping path="/supplier/*"/>来过滤 ...