需求:
1、查
输入:www.oldboy.org获取当前backend下的所有记录
2、新建
输入:
arg = {
'bakend': 'www.oldboy.org',
'record':{
'server': '100.1.7.9',
'weight': 20,
'maxconn': 30
}
}
3、删除
输入:
arg = {
'bakend': 'www.oldboy.org',
'record':{
'server': '100.1.7.9',
'weight': 20,
'maxconn': 30
}
}
#-*-coding:utf-8-*-
def recd_add():
add_inf_tmp = input("请输入要增加的内容:")
add_inf = eval(add_inf_tmp)
with open("haproxy",'r+',encoding='utf-8') as file:
for line in file:
if 'backend' in line:
line_ful = "backend {website}\n".format(website=add_inf['backend'])
if line == line_ful():
return print('The record already exits.')
file.write('\nbackend {backend}\n '.format(backend=add_inf['backend']))
file.write('\tserver {red1} weight {num1} maxconn {num2}\n'.format(red1=add_inf['record']['server'],
num1 = add_inf['record']['weight'],
num2 = add_inf['record']['maxconn']))
return print('Adding record successfully. ')
def recd_read():
read_inf = ("请输入要读取的地址:")
with open("haproxy","r",encoding='utf-8') as file:
for line in file:
if "backend" in line:
line_ful ="backend {website}\n".format(website=read_inf)
if line ==line_ful:
rd = file.readline()
return print(rd)
return 'The record do not exit.'
def recd_delete_stupid():
del_inf = eval(input("请输入要删除的地址内容:"))
index_old_file = 0
index_new_file = 0
with open("haproxy","r+",encoding='utf-8') as file:
file_tmp = open("haproxy_tmp",'w')
line_ful = "backend {website}\n".format(website=del_inf['backend'])
for line in file:
if 'backend' not in line:
file_tmp.write(line)
index_new_file +=1
index_old_file +=1
elif line != line_ful:
file_tmp.write(line)
index_new_file +=1
index_old_file +=1
else:
print('Delete {line}\n \t{content}'.format(line=line, content=file.readline()))
index_old_file +=1
file_tmp.close()
file_tmp = open("haproxy_tmp", 'r')
if index_old_file ==index_new_file:
file_tmp.close()
return print('The input content is wrong!')
else:
with open("haproxy", "w", encoding='utf-8') as file:
for line in file_tmp:
file.write(line)
file_tmp.close()
return print('The record has been delete.')
choice_recd = ['add', 'delete', 'read','quit'] #用来判断输入的内容对不对
while True:
choice = input("Please input 'add', 'delete', 'read','quit'")
if choice in choice_recd: #判断输入的内容对不对
if choice == 'add':
recd_add()
elif choice == 'read':
recd_read()
elif choice == 'delete':
recd_delete_stupid()
elif choice == 'quit':
break