需要掌握的知识:

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. html中select标签根据枚举获得值的总结

    不知不觉在公司一个多月了,这一个月做了一个支票申请的web页面功能,都不是特别难,审核有公司给的工作流,分页工具和很多公用工具公司也都给了,所以觉得难度都不是很大.今天主管让我们修改了以前做的项目的代 ...

  2. Google C++单元测试框架GoogleTest---Extending Google Test by Handling Test Events

    Google TestExtending Google Test by Handling Test Events Google测试提供了一个事件侦听器API,让您接收有关测试程序进度和测试失败的通知. ...

  3. JS判断用户手机是IOS还是Android

    $(function () { var u = navigator.userAgent, app = navigator.appVersion; var isAndroid = u.indexOf(' ...

  4. SQL SERVER 2014 下IF EXITS 居然引起执行计划变更的案例分享

    这个问题是在SQL SERVER 2005 升级到SQL SERVER 2014的测试过程中一同事发现的.我觉得有点意思,遂稍微修改一下脚本展示出来,本来想构造这样的一个案例来演示,但是畏惧麻烦,遂直 ...

  5. Could not obtain information about Windows NT group/user 'xxxx\xxxx', error code 0x5

    案例描述 昨晚踢球回来,接到电话说一个系统的几个比较重要作业出错,导致系统数据有些问题.让我赶紧检查看看.检查作业日志时发现,作业报如下错误(关键信息用xxx替换) The job failed.  ...

  6. 一道常被人轻视的前端JS面试题

    前言 年前刚刚离职了,分享下我曾经出过的一道面试题,此题是我出的一套前端面试题中的最后一题,用来考核面试者的JavaScript的综合能力,很可惜到目前为止的将近两年中,几乎没有人能够完全答对,并非多 ...

  7. VS 中關於附加到進程中調試 的問題。

    在使用Vs 2012 時,項目發佈到Local IIS 中,如果在調試某個頁面中時,都要F5--> Login --> Debug 很繁瑣,下列有一種較快捷的方式,能夠更快的調試代碼. 1 ...

  8. SQL Server 2008 R2——使用FOR XML PATH实现多条信息按指定格式在一行显示

    =================================版权声明================================= 版权声明:原创文章 谢绝转载  请通过右侧公告中的“联系邮 ...

  9. Spark基本工作流程及YARN cluster模式原理(读书笔记)

    Spark基本工作流程及YARN cluster模式原理 转载请注明出处:http://www.cnblogs.com/BYRans/ Spark基本工作流程 相关术语解释 Spark应用程序相关的几 ...

  10. [原创]kali linux下破解wifi密码以及局域网渗透

    无线破解是进行无线渗透的第一步.破解无线目前只有两种方法:抓包.跑pin. 破解无线方法一:抓包.我是在kali linux下进行的. 将无线网卡的模式调为监听模式. airmon-ng start ...