#!/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. 一元回归_ols参数解读(推荐AAA)

    sklearn实战-乳腺癌细胞数据挖掘(博客主亲自录制视频教程) https://study.163.com/course/introduction.htm?courseId=1005269003&a ...

  2. 这年头不会点Git真不行!!!

    版本控制 说到版本控制,脑海里总会浮现大学毕业是写毕业论文的场景,你电脑上的毕业论文一定出现过这番景象! 1 2 3 4 5 6 7 8 9 10 11 毕业论文_初稿.doc 毕业论文_修改1.do ...

  3. Java集合框架(set)

    set继承自collection接口,其子类和子接口如下: set的共同特性:不能添加相同的元素,通常无法记住元素添加的顺序 1.HashSet类 判断两元素相同的标准:1.equals方法返回tru ...

  4. 2017 ACM-ICPC 西安网络赛 F.Trig Function Chebyshev多项式

    自己太菜,数学基础太差,这场比赛做的很糟糕.本来想吐槽出题人怎么都出很数学的题,现在回过头来想还是因为自己太垃圾,竞赛就是要多了解点东西. 找$f(cos(x))=cos(nx)$中$x^m$的系数模 ...

  5. CS48 D BIT

    统计一个点对应的和它严格右下方的点,点对数量.由于数据规模很大,不能直接上二维的前缀和,先排一维序,然后用BIT维护前缀和即可. /** @Date : 2017-09-14 20:17:30 * @ ...

  6. DLL初试

    环境: VC++6.0 步骤: 1.建立一个WIN32 DYNAMIC-LINK LIBRARY工程,编写CPP文件,文件内容例如: #include "stdafx.h" #in ...

  7. User-Agent大全

    一.基础知识篇: Http Header之User-Agent User Agent中文名为用户代理,是Http协议中的一部分,属于头域的组成部分,User Agent也简称UA.它是一个特殊字符串头 ...

  8. XGBoost与LightGBM对比分析(转)

    尊重原创 来源: https://blog.csdn.net/a790209714/article/details/78086867   XGBoost的四大改进: ①改进残差函数 不用Gini作为残 ...

  9. 在Nginx服务器上屏蔽IP

    采集和防止采集是一个经久不息的话题,一方面都想搞别人的东西,另一方面不想自己的东西被别人搞走. 本文介绍如何利用nginx屏蔽ip来实现防止采集,当然也可以通过iptable来实现. 1.查找要屏蔽的 ...

  10. linux用户修改用户shell

    要拒绝系统用户登录,可以将其shell设置为/usr/sbin/nologin或者/bin/false # usermod -s /usr/sbin/nologin username 或者 # use ...