s12-day03-work01 python修改haproxy配置文件(初级版本)
#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import sys,time
import module ha = './haproxy.conf'
#选择功能
def chooseView(choice):
if choice == 1: #获取配置文件所有内容
print(module.getAllContent(ha))
choice1 = input("请选择是否要继续(y/n):").strip()
if choiceIf(choice1) == True:
print("你选择的是继续,系统即将返回到系统主页!")
time.sleep(1)
chooseView(showView())
if choiceIf(choice1) == False:
print("你选择的是不继续操作,系统将退出!感谢你的使用!")
time.sleep(1)
sys.exit(0) if choice == 2:
module.addLabelRecord(ha,getInputConnet())
if choice == 3:
module.delLabelRecord(ha,getInputConnet())
if choice == 4:
module.chgLabelRecord(ha)
if choice == 'q':
print("系统即将退出,感谢你的使用!")
time.sleep(1)
sys.exit(0) #判断用户输入,是否继续或返回
def choiceIf(choice):
if choice.isalpha():
if choice == 'Y' or choice == 'y':
return True
elif choice == 'N' or choice == 'n':
return False
else:
print("你的指令系统暂不支持!系统即将退出!")
time.sleep(1)
sys.exit(2)
else:
print("你输入的字符格式有误,系统将默认返回到主页!")
time.sleep(1)
chooseView(showView()) def showView():
print('''
****欢迎使用haproxy配置文件修改系统****
\t[1]获取配置文件信息\t\t[2]增加模块配置
\t[3]删除模块配置 \t\t[4]修改模块配置
\t[q]退出系统
************************************
''')
while True:
count = 0
if count < 3:
choice = input("\t请选择相应指令:").strip()
if choice.isdigit():
choice = int(choice)
if choice > 0 and choice < 5:
return choice
else:
count += 1
print("你的输入已超出指令范围!")
elif choice == 'q':
return choice
else:
count += 1
print("请输入正确的指令,指令为[1-4]的整型或q字符!")
else:
print("对不起,你的输入错误次数已达3次,系统即将退出,感谢你的使用!")
time.sleep(1)
sys.exit(1) #获取用户输入字典
def getInputConnet():
get_input_dict = {}
count = 0
while True:
if count < 3:
get_input_dict['label'] = input("请输入你需要增加记录内容的模块名称:").strip()
get_input_dict['server'] = input("请输入server字段值:").strip()
get_input_dict['weight'] = input("请输入weight字段值:").strip()
get_input_dict['maxconn'] = input("请输入maxconn字段值:").strip()
# if get_input_dict['label'].isalpha():
if get_input_dict['label']:
getall_dict = module.getAllContentDict(ha) #获取配置文件总的字典
if get_input_dict['label'] in getall_dict.keys(): #用户输入的moudle在文件中存在,那就直接在原有的基础上增加记录值
return get_input_dict
# else: #label模块不存在,根据用户选择是否要创建
# choice = input("你选择的模块不存在,是否要创建(y/n):").strip()
# if choiceIf(choice) == True:
# print("你选择的是继续,系统即将创建moudle %s!" % get_input_dict['label'])
# print('''即将创建的模块内容为:
# \t%s
# \t\t\tserver %s weight %s maxconn %s\n
# ''' % (get_input_dict['label'],get_input_dict['server'],get_input_dict['weight'],get_input_dict['maxconn']))
# return get_input_dict
# if choiceIf(choice) == False:
# print("你选择的是不继续操作,系统将退出!感谢你的使用!")
# time.sleep(1)
# sys.exit(0) else:
count += 1
print("模块名称Label需要全为字母的字符!")
else: #输错3次之后返回系统主页
print("你的输入错误次数已达3次,系统即将返回主页!")
time.sleep(1)
chooseView(showView()) #main
if __name__ == "__main__":
ha = './haproxy.conf'
chooseView(showView())
index.py
#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
''' import json,os,shutil,time
import index ha = "./haproxy.conf" #备份配置文件
def haBak(ha):
shutil.copyfile(ha,ha + '.bak') #获取文件行数
def countnum(filename):
files = open(filename)
data = files.read()
files.flush()
files.close()
return data.count('\n') #获取文件所有内容
def getAllContent(ha):
with open(ha,'r+') as f:
all_content = f.read() #获取文件所有内容
return all_content #获取文件内容
def getAllContentDict(ha):
with open(ha,'r+') as f:
all_content = f.read() #获取文件所有内容,类型为str
all_content_dict = {} #初始化一个总的字典。将文件的所有内容都存档到该字典中
record = [] #初始化一个record列表,该列表用来存储每个label下面的记录值
for line in all_content.split('\n'): #按照换行符进行每行内容遍历
label_dict_temp = {} #初始化一个label的临时字典,该字典记录的是{label:record}
if not line.startswith(" "): #判断每行内容是否为8个空格字符开头,这里取否,取的是label值
record = [] #每次获取label值都要对record列表进行初始化,这里修改的是全局变量
label_dict_temp[line] = record ##将record列表作为values值添加到label_dict_temp临时字典中
else: #每行内容为8个空格字符开头,取得是label下面的record值
record.append(line.strip()) #将该行的值append到record列表中,每行记录值以元素的身份存在在record中
all_content_dict.update(label_dict_temp) #将获取的{label:record}字典更新到总的字典中
return all_content_dict #最后返回值为配置文件的label内容 #增加模块记录值
def addLabelRecord(ha,dict_input):
with open(ha,'r') as all_content,open(ha+'.new','w+') as all_content_new:
all_content_dict = getAllContentDict(ha)
add_str = " server %s %s weight %s maxconn %s\n" % (dict_input['server'],dict_input['server'],dict_input['weight'],dict_input['maxconn'])
if dict_input['label'] in all_content_dict.keys():
flag = False
for line in all_content.readlines():
all_content_new.write(line)
if line.strip('\n') == dict_input['label']:
flag = True
continue
if flag:
all_content_new.write(add_str)
flag = False
else:
pass print("增加成功!")
choice = input("请选择是否要更新到线上(y/n):").strip()
if index.choiceIf(choice) == True:
print("你选择的是更新到线上,系统即将把修改后的文件发布到线上并返回系统首页!")
if os.path.exists(ha + '.bak'):
os.remove(ha + '.bak')
os.rename(ha,ha+'.bak')
os.rename(ha+'.new',ha)
time.sleep(1)
index.chooseView(index.showView())
if index.choiceIf(choice) == False:
print("你选择的是放弃更新,系统即将返回系统首页!")
if os.path.exist(ha + '.new'):
os.remove(ha + '.new')
index.chooseView(index.showView()) def delLabelRecord(ha,dict_input):
with open(ha,'r') as all_content,open(ha+'.new','w+') as all_content_new:
all_content_dict = getAllContentDict(ha)
del_str = " server %s %s weight %s maxconn %s\n" % (dict_input['server'],dict_input['server'],dict_input['weight'],dict_input['maxconn'])
if dict_input['label'] in all_content_dict.keys():
flag = False
for line in all_content.readlines():
if line.strip('\n') == dict_input['label']:
flag = True
all_content_new.write(line)
continue
if flag == True and line == del_str:
flag = False
continue
all_content_new.write(line)
else:
pass
print("删除成功!")
choice = input("请选择是否要更新到线上(y/n):").strip()
if index.choiceIf(choice) == True:
print("你选择的是更新到线上,系统即将把修改后的文件发布到线上并返回系统首页!")
if os.path.exists(ha + '.bak'):
os.remove(ha + '.bak')
os.rename(ha,ha+'.bak')
os.rename(ha+'.new',ha)
time.sleep(1)
index.chooseView(index.showView())
if index.choiceIf(choice) == False:
print("你选择的是放弃更新,系统即将返回系统首页!")
if os.path.exists(ha + '.new'):
os.remove(ha + '.new')
index.chooseView(index.showView()) def chgLabelRecord(ha):
#获取用户修改label记录值
print("下面请按照提示输入你要修改的记录值!")
dict_input1 = index.getInputConnet()
print("下面请按照提示输入你要修改后的记录值!")
dict_input2 = index.getInputConnet()
with open(ha,'r') as all_content,open(ha+'.new','w+') as all_content_new:
all_content_dict = getAllContentDict(ha)
old_str = " server %s %s weight %s maxconn %s\n" % (dict_input1['server'],dict_input1['server'],dict_input1['weight'],dict_input1['maxconn'])
new_str = " server %s %s weight %s maxconn %s\n" % (dict_input2['server'],dict_input2['server'],dict_input2['weight'],dict_input2['maxconn'])
print(new_str)
if dict_input1['label'] in all_content_dict.keys():
flag = False
for line in all_content.readlines():
if line.strip('\n') == dict_input1['label']:
flag = True
all_content_new.write(line)
continue
if flag == True and line == old_str:
all_content_new.write(new_str)
flag = False
continue
all_content_new.write(line)
else:
pass
print("修改成功!")
choice = input("请选择是否要更新到线上(y/n):").strip()
if index.choiceIf(choice) == True:
print("你选择的是更新到线上,系统即将把修改后的文件发布到线上并返回系统首页!")
if os.path.exists(ha + '.bak'):
os.remove(ha + '.bak')
os.rename(ha,ha+'.bak')
os.rename(ha+'.new',ha)
time.sleep(1)
index.chooseView(index.showView())
if index.choiceIf(choice) == False:
print("你选择的是放弃更新,系统即将返回系统首页!")
if os.path.exists(ha + '.new'):
os.remove(ha + '.new')
index.chooseView(index.showView())
module.py
github代码更新地址:https://github.com/swht/projects/tree/master/day03/
s12-day03-work01 python修改haproxy配置文件(初级版本)的更多相关文章
- 用python修改haproxy配置文件
需求: 当用户输入域名的时候,显示出来下面的记录 当用户需要输入添加纪录的时候,添加到你需要的那个域名下面 global log 127.0.0.1 local2 daemon maxconn 256 ...
- Python3.5 day3作业二:修改haproxy配置文件。
需求: 1.使python具体增删查的功能. haproxy的配置文件. global log 127.0.0.1 local2 daemon maxconn 256 log 127.0.0.1 lo ...
- python之haproxy配置文件操作(第三天)
作业: 对haproxy配置文件进行操作 要求: 对haproxy配置文件中backend下的server实现增删改查的功能 一.这个程序有二个版本 1. python2.7版本见haproxy_py ...
- python基础-修改haproxy配置文件
需要掌握的知识: 1.函数 2.文件处理 3.tag的用法 4.程序的解耦 需求: 1:查询 2:添加 3:删除 4:修改 5:退出 haproxy.conf 配置文件内容: global log 1 ...
- Python小程序之动态修改Haproxy配置文件
需求如下: 1.动态的查询添加删除haproxy节点信息 2.程序功能:add(添加).Del(删除).Query(查询) 3.添加时实例字符串为: {'backend': 'www.oldboy. ...
- python基础-4.1 open 打开文件练习:修改haproxy配置文件
1.如何在线上环境优雅的修改配置文件? 配置文件名称ini global log 127.0.0.1 local2 daemon maxconn 256 log 127.0.0.1 local2 in ...
- python编辑修改haproxy配置文件--文件基础操作
一.需求分析 有查询,删除,添加的功能 查询功能:查询则打印查询内容,如果不存在也要打印相应的信息 删除功能:查询到要删除内容则删除,打印信息. 添加功能:同上. 二.流程图 三.代码实现 本程序主要 ...
- python基础修改haproxy配置文件
1.通过eval(),可以将字符串转为字典类型. 2.Encode过程,是把python对象转换成json对象的一个过程,常用的两个函数是dumps和dump函数.两个函数的唯一区别就是dump把py ...
- Python 修改ha配置文件
任务要求: 1.用户输入字符串 {"backend": "test.oldboy.org","record":{"server&q ...
随机推荐
- 用dom4j修改xml(增加修改节点)
用dom4j修改xml(增加修改节点) 博客分类: Java XMLJavaMyeclipseServlet 使用dom4j修改解析xml,xml文件的位置是配置在xml.properties文件中 ...
- 「Django」rest_framework学习系列-解析器
满足两个要求,request.Post中才有值 1.请求头要求:请求头中的Content-Type为application/x-www-form-urlencoded 2.数据格式要求 name=x& ...
- JavaSE的学习路线
基于现阶段的JavaEE学习的对象,主要是趋向于Web的方向,主要就是说在JavaWeb的基础上进行进一步的开发和学习,下面我会将自己总结的对于自己的一点关于JavaEE学习路线会逐步讲解. 第一部分 ...
- 2017北京国庆刷题Day2 afternoon
期望得分:100+100+50=250 实际得分:100+70+50=220 T1 最大值(max) Time Limit:1000ms Memory Limit:128MB 题目描述 LYK有一 ...
- mongoDB与sql聚合操作对应图
SQL Terms, Functions, and Concepts MongoDB Aggregation Operators WHERE $match GROUP BY $group HAVING ...
- 《HTML5编程之旅》系列三:WebSockets 技术解析
本文主要研究HTML5 WebSockets的使用方法,它是HTML5中最强大的通信功能,定义了一个全双工的通信信道,只需Web上的一个Socket即可进行通信,能减少不必要的网络流量并降低网络延迟. ...
- 【BZOJ】1492: [NOI2007]货币兑换Cash
[题意]初始资金s,有两种金券A和B,第i天,买入时将投入的资金购买比例为rate[i]的两种股票,卖出时将持有的一定比例的两种股票卖出,第i天股票价格为A[i],B[i],求最大获利.n<=1 ...
- 【BZOJ】3527: [Zjoi2014]力 FFT
[参考]「ZJOI2014」力 - FFT by menci [算法]FFT处理卷积 [题解]将式子代入后,化为Ej=Aj-Bj. Aj=Σqi*[1/(i-j)^2],i=1~j-1. 令f(i)= ...
- js和php的时间戳和时间的转化
js时间戳转化为时间 //时间戳转时间 function time(sj) { var now = new Date(sj*1000); var year =now.getFullYear(); va ...
- 2017 ACM暑期多校联合训练 - Team 3 1008 HDU 6063 RXD and math (莫比乌斯函数)
题目链接 Problem Description RXD is a good mathematician. One day he wants to calculate: ∑i=1nkμ2(i)×⌊nk ...