#!/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. 如何在Linux系统上安装QQ

    转载自KKK博客 首先我们需要在wine的官网上安装一个wine. https://wiki.winehq.org/Ubuntu_zhcn 按照上面的提示一步步来,做完之后点下面的链接下载 https ...

  2. opencv函数制作的时钟模型

    http://www.cnblogs.com/sytu/p/4192652.html 在秒针模型的基础上添加了分针和时针,并且添加了暂停控件和设置时间的功能. #include"cv.h&q ...

  3. Rabbitmq--topic

    一.前言 前面讲到direct类型的Exchange路由规则是完全匹配binding key与routing key,但这种严格的匹配方式在很多情况下不能满足实际业务需求.topic类型的Exchan ...

  4. echo 不换行

    原文 http://blog.sina.com.cn/s/blog_4da051a6010184uk.html echo -n 不换行输出   $echo -n "123" $ec ...

  5. windows下libcurl与zlib和ssl共同编译

    下载了curl 7.37,在project里有各个版本VS对应的项目文件,我们选择合适的打开即可以编译,根据不同的项目配置输出想要的库,比如可以切换多种SSL库,dll/lib,debug/relea ...

  6. mysql \G

    mysql 命令区分大小写.ego       (\G) Send command to mysql server, display result vertically. go        (\g) ...

  7. Python学习笔记(四十七)SMTP发送邮件

    摘抄自:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001432005226 ...

  8. JVM学习十三:JVM之堆分析

    本章进入JVM学习的最后一节,此节主要分析的是堆,因为堆是JAVA程序中最常用使用到的地方,因此对这个地方有必要进行下细致的分析特别是OOM,言归正传,进入正文. 一.内存溢出(OOM)的原因 在JV ...

  9. 【BZOJ】4872: [Shoi2017]分手是祝愿 期望DP

    [题意]给定n盏灯的01状态,操作第 i 盏灯会将所有编号为 i 的约数的灯取反.每次随机操作一盏灯直至当前状态能够在k步内全灭为止(然后直接灭),求期望步数.n,k<=10^5. [算法]期望 ...

  10. JQuery对RadioButton和CheckButton的操作

    js对RadioButton和CheckButton的操作,在网站开发中会经常遇到,而JQuery操作RadioButton和CheckButton非常便捷.小编觉得网站开发人员有必要熟练掌握.所以小 ...