python基础-修改haproxy配置文件

时间:2023-03-09 07:39:32
python基础-修改haproxy配置文件

需要掌握的知识:

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)