#!/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配置文件(初级版本)的更多相关文章

  1. 用python修改haproxy配置文件

    需求: 当用户输入域名的时候,显示出来下面的记录 当用户需要输入添加纪录的时候,添加到你需要的那个域名下面 global log 127.0.0.1 local2 daemon maxconn 256 ...

  2. Python3.5 day3作业二:修改haproxy配置文件。

    需求: 1.使python具体增删查的功能. haproxy的配置文件. global log 127.0.0.1 local2 daemon maxconn 256 log 127.0.0.1 lo ...

  3. python之haproxy配置文件操作(第三天)

    作业: 对haproxy配置文件进行操作 要求: 对haproxy配置文件中backend下的server实现增删改查的功能 一.这个程序有二个版本 1. python2.7版本见haproxy_py ...

  4. python基础-修改haproxy配置文件

    需要掌握的知识: 1.函数 2.文件处理 3.tag的用法 4.程序的解耦 需求: 1:查询 2:添加 3:删除 4:修改 5:退出 haproxy.conf 配置文件内容: global log 1 ...

  5. Python小程序之动态修改Haproxy配置文件

    需求如下: 1.动态的查询添加删除haproxy节点信息 2.程序功能:add(添加).Del(删除).Query(查询) 3.添加时实例字符串为:  {'backend': 'www.oldboy. ...

  6. python基础-4.1 open 打开文件练习:修改haproxy配置文件

    1.如何在线上环境优雅的修改配置文件? 配置文件名称ini global log 127.0.0.1 local2 daemon maxconn 256 log 127.0.0.1 local2 in ...

  7. python编辑修改haproxy配置文件--文件基础操作

    一.需求分析 有查询,删除,添加的功能 查询功能:查询则打印查询内容,如果不存在也要打印相应的信息 删除功能:查询到要删除内容则删除,打印信息. 添加功能:同上. 二.流程图 三.代码实现 本程序主要 ...

  8. python基础修改haproxy配置文件

    1.通过eval(),可以将字符串转为字典类型. 2.Encode过程,是把python对象转换成json对象的一个过程,常用的两个函数是dumps和dump函数.两个函数的唯一区别就是dump把py ...

  9. Python 修改ha配置文件

    任务要求: 1.用户输入字符串 {"backend": "test.oldboy.org","record":{"server&q ...

随机推荐

  1. 洛谷P2563 [AHOI2001]质数和分解

    题目描述 任何大于 1 的自然数 n 都可以写成若干个大于等于 2 且小于等于 n 的质数之和表达式(包括只有一个数构成的和表达式的情况),并且可能有不止一种质数和的形式.例如,9 的质数和表达式就有 ...

  2. ppt述职摘要

    1.工作总结 1)做了什么 2)做的怎么样 3)还要做什么 2.个人成长和团队成长 3.个人目标和团队目标 1)时间+量化(具体说明) 2)预期效果 3)团队凝聚力 4.展望

  3. Hibernate学习(5)- session的get与load方法对比

    1.共同点:get和load都是根据Id单条查询获取对象 org.hibernate.Session.load(Class<User> theClass, Serializable id) ...

  4. Tensorboard教程:监控指标可视化

    Tensorflow监控指标可视化 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考文献 强烈推荐Tensorflow实战Google深度学习框架 实验平台: Tensorflow1.4. ...

  5. js控制treeview默认展开

    bootStrapTreeview 在bootstrap的treeview官网,可以找到这个方法,用js控制可以写成:$('#xxx').treeview('collapseNode',{silent ...

  6. ZooKeeper在线迁移

    在至少有一个Leader存在的前提下,进行Zookeeper的在线增量.在线减量.在线迁移 在全过程中ZooKeeper不停止服务 注意事项 首先,当我们要从3台扩充到5台时,应保证集群不停止服务. ...

  7. Arrays.asList方法遇到的问题

    在使用Arrays.asList(T...a)方法时,遇到了 java.lang.UnsupportedOperationException  异常. 后来发现,该方法返回的类型是Arrays$Arr ...

  8. 816E. Karen and Supermarket 树形DP

    LINK 题意:给出n个商品,除第一个商品外,所有商品可以选择使用优惠券,但要求其前驱商品已被购买,问消费k以下能买几个不同的商品 思路:题意很明显就是树形DP.对于一个商品有三种选择,买且使用优惠券 ...

  9. 使用HttpClient4来构建Spring RestTemplate

    Spring RestTemplate简单说明 现在REST服务已经很普及了,在我们的程序中,经常会需要调用REST API,这时候会有很多选择,原始一点的JDK自带的,再进一步点使用HttpClie ...

  10. IO流-文件拷贝

    其实文件的拷贝还是文件读取写入的应用,实际是读取此路径上的文件,然后写入到指定路径下的文件. 代码举例: import java.io.*; import java.lang.*; class Tes ...