# 增删改查haproxy
def add_conf(add_domain,add_record):
"""
增加记录
:param add_domain:
:param add_record:
:return:
"""
with open("haproxy.conf", encoding="utf8") as file, \
open("add_haproxy.conf", 'w', encoding="utf8") as afile:
for line in file:
if line.strip().startswith("backend") and add_domain in line:
line = "".join([line,"\n","\t\t",add_record.strip(),'\n'])
afile.write(line)
print("增加记录成功")
def del_conf(del_domain,num):
"""
输入删除的域名和序号,删除源文件对应的行
:param del_domain:
:param num:
:return:
"""
with open("haproxy.conf", encoding="utf8") as file, \
open("del_haproxy.conf", 'w', encoding="utf8") as dfile:
l = find_conf(del_domain)
print(l[(num-1)])
for line in file:
if line.strip() == l[num-1]:
continue
else:
dfile.write(line)
print("删除成功")
def change_conf(ch_domain, ch_num, ch_record):
with open("haproxy.conf", encoding="utf8") as file, \
open("ch_haproxy.conf", 'w', encoding="utf8") as chfile:
l = find_conf(ch_domain)
for line in file:
if line.strip() == l[ch_num - 1]:
line = "\t\t"+ch_record+"\n"
chfile.write(line)
print("修改成功")
def find_conf(domain):
"""
查询并打印server信息
:param domain: 查询域名
:return: 包含server信息的列表L
"""
flag = False
l = []
with open("haproxy.conf", encoding="utf8") as find_file:
for lines in find_file:
if lines.strip().startswith("backend") and lines.strip().endswith(domain):
flag = True
continue
if lines.strip().startswith("backend") and flag == True:
flag = False
if flag == True:
l.append(lines.strip())
return l
def menu():
print( """-------------------
1.查询
2.增加
3.删除
4.修改
------------------------""")
def main():
menu()
choice=int(input("请输入操作序号"))
# 查询
if choice == 1:
name = input("请输入要查询的域名")
server_list = find_conf(name) # 拿到含有server信息的列表
count =1
for i in server_list:
print(count,i)
count += 1
# 增加
if choice == 2:
add_domain = input("请输入要增加的域名")
add_record = input("请输入要增加的record")
add_conf(add_domain,add_record)
# 删除
if choice == 3:
del_domain = input("请输入要删除的域名")
del_list = find_conf(del_domain)
count = 1
for i in del_list:
print(count, i)
count += 1
del_num = int(input("请输入要删除的序号"))
del_conf(del_domain, del_num)
# 修改
if choice == 4:
ch_domain = input("请输入要修改的域名")
ch_list = find_conf(ch_domain)
count = 1
for i in ch_list:
print(count, i)
count += 1
ch_num = int(input("请输入需要修改的序号"))
ch_record = input("请输入需要修改record")
change_conf(ch_domain, ch_num, ch_record)
while True:
main()
转载于:https://www.cnblogs.com/zouruncheng/p/6678998.html