最近在学习Python的过程中老师布置的作业在线修改haproxy配置文件,写了好久终于有点思路,这里将代码记录如下:
#!/usr/bin/env python
# -*- coding:utf8 -*-
import os
import json
def fetch(backend):
fetch_list = []
with open('ha') as obj:
flag = False
for line in obj:
# line 每一行,
if line.strip() == "backend %s" % backend:
flag = True
continue
# 判断,如果当前是 backend开头,不再放
if flag and line.strip().startswith('backend'):
break
if flag and line.strip():
fetch_list.append(line.strip())
return fetch_list
#result = fetch("buy.oldboy.org")
#print result
def adds(dict_info):
#s = '{"backend": "www.oldboy.org","record":{"server": "100.1.7.9","weight": 20,"maxconn": 30}}'
backend_title = dict_info.get('backend')
current_title = "backend %s" % backend_title
current_record = "server %s %s weight %s maxconn %s" % (dict_info['record']['server'],dict_info['record']['server'],dict_info['record']['weight'],dict_info['record']['maxconn'])
# 获取制定backend下的所有记录
fetch_list = fetch(backend_title)
#print fetch_list
# backend是否存在
if fetch_list:
#pass # 存在backend,则只需再添加记录
# 1,要插入的记录,存在
# 2,要插入的记录,不存在
if current_record in fetch_list:
pass
else:
fetch_list.append(current_record)#如果不存在直接将current_record追加到fetch_list中
# 此时fetch_list为处理完的新列表
with open('ha') as read_obj, open('ha.new', 'w') as write_obj:
flag = False
has_write = False
for line in read_obj:#读取原配置文件
if line.strip() == current_title:#如果读取的行内容与current_title相等,则把current_title写入到文件中,然后就跳出本次循环,
write_obj.write(line)
flag = True
continue
if flag and line.strip().startswith('backend'):#如果flag为真并且读取的line.strip内容是以"backend开头",则将flag置False
flag = False
if flag:
#如果flag为True新列表fetch_list所有数据一行一行的写入到新配置文件,即遍历原配置文件中current_title标签下的current_record记录,如果curent_record有三条,则循环三次,每循环一次就将fetch_list完整遍历一次的一条一条地写入到新配置文件,所以这里要用一个标识符has_write作为判断是否写入,如果已经写入了就不再继续往新配置文件中写入
if not has_write:
for new_line in fetch_list:
temp = "%s %s \n" %(" "*8, new_line)
write_obj.write(temp)
has_write = True
else:
# 不满足以上的各种情况则直接将内容写入新配置文件
write_obj.write(line)
else:
#pass,如果不存在backend,则添加backend和current_record
# current_title,current_record
# 直接打开文件
with open('ha') as read_obj, open('ha.new', 'w') as write_obj:
for line in read_obj:
write_obj.write(line)
write_obj.write('\n')
write_obj.write(current_title+'\n')
temp = "%s %s \n" %(" "*8, current_record)
write_obj.write(temp)
#s = '{"backend": "test.oldboy.org","record":{"server": "10.10.10.9","weight": 20,"maxconn": 3000}}'
#data_dict = json.loads(s)
#adds(data_dict)
def remove(dict_info):
backend_title = dict_info.get('backend')
current_title = "backend %s" % backend_title
current_record = "server %s %s weight %s maxconn %s" % (dict_info['record']['server'],dict_info['record']['server'],dict_info['record']['weight'],dict_info['record']['maxconn'])
# 获取制定backend下的所有记录
fetch_list = fetch(backend_title)
if fetch_list:
pass
else:
if current_record not in fetch_list:
pass
else:
fetch_list[fetch_list.index(current_record)]
if len(fetch_list) > 0:
fetch_list.insert(0, backend_title)
with open('ha') as read_file, open('ha.new', 'w') as write_file:
flag = False
has_write = False
for line in read_file:
line_strip = line.strip()
if line_strip == backend_title:
flag = True
continue
if flag and line_strip.startswith('backend'):
flag = False
if not flag:
write_file.write(line)
else:
if not has_write:
for i in fetch_list:
if i.startswith('backend'):
write_file.write(i+'\n')
else:
write_file.write("%s%s\n" % (8*" ", i))
has_write = True
os.rename("ha", 'ha.bak')
os.rename("ha.new", 'ha')
if __name__ == '__main__':
print '1、获取;2、添加;3、删除'
num = raw_input('请输入序号:')
data = raw_input('请输入内容:')
if num == '1':
fetch(data)
else:
dict_data = json.loads(data)
if num == '2':
add(dict_data)
elif num == '3':
remove(dict_data)
else:
pass