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 ...
随机推荐
- 2016-2017 ACM-ICPC Southwestern European Regional Programming Contest (SWERC 2016) F dfs序+树状数组
Performance ReviewEmployee performance reviews are a necessary evil in any company. In a performance ...
- Ubuntu在vncviewer下Tab键失效
打开命令行,运行如下命令即可解决: xfconf-query -c xfce4-keyboard-shortcuts -p /xfwm4/custom/'<'Super'>'Tab -r ...
- plantuml使用教程【转】
plantuml使用教程[转] Table of Contents 前言 什么是PlantUML 在Emacs里配置PlantUML(参考:Run it from Emacs) 其他软件里的Pla ...
- libxml移植到android
libxml是C语言写的xml解析库,是我们开发可移植程序的首选,下面讲述将其移植到android的步骤 1.下载已经配置好的源代码包android_libxml2.rar http://pan.ba ...
- 3.redis设计与实现--字典
1.包括三个结构体:字典结构体+哈希表结构体+哈希节点结构体 2.如何解决哈希冲突? 答:redis使用的是链地址法来解决哈希冲突的,每个链表节点有一个next指针,最新加入的节点会放在链表的头部. ...
- UVA 1390 Interconnect
https://vjudge.net/problem/UVA-1390 题意: 给出n个点m条边的无向图, 每次随机加一条非自环的边,(加完后可出现重边), 添加每条边的概率是相等的 求使图连通的期望 ...
- MappedByteBuffer以及ByteBufer的底层原理
最近在用java中的ByteBuffer,一直不明所以,尤其是对MappedByteBuffer使用的内存映射这个概念云里雾里. 于是首先补了物理内存.虚拟内存.页面文件.交换区的只是:小科普——物理 ...
- java-jdbc-mysql:实现数据库表的增删改查
以数据库test下数据表student(sno,sname,ssex,sage,sdept)为例: student表中的已有的所有记录:
- 母版页 VS shtml—ASP.NET细枝末节(3)
这算是html的重用吧? 网页很多地方长得一样,也有不一样的地方. 把网页中一样的地方,提取出来,形成一个文档. 在其他网页中引用,是网站开发的一个传统的思维. 当然不同的技术有不同的表现形式. 例如 ...
- 微信小程序开发(一)准备开发环境
1.成为微信公众平台开发者 成为微信公众平台的开发者,是小程序开发的首要条件.只有成为微信公众平台的开发者,才可以使用公众平台的各种开发接口.如果你已经是开发者,则可以跳过本章. (1)进入微信公众平 ...