s13 day3作业
ha_proxy配置文件修改程序
ha_file 为存储配置信息的文件。运行的时候对该文件进行操作。
1.查询信息:用户输入域名,获得域名相关信息
2.修改配置文件:用户输入的格式应该为 {"backend": "test.oldboy.org","record":{"server": "100.1.7.9","weight": 20,"maxconn": 30}}
然后执行判断,如果输入的backend存在,则判断对应的信息是否重复,如果重复,则提醒用户,同时对配置文件不做更改。
如果输入的信息与原配置信息不符,则追加到相应的backend下。
如果输入的backend不存在,则追加到文件末尾。
3.删除信息:用户输入存在的域名,则删除域名和相应的配置文件。如果不存在,则提示错误。
下面是ha_file文件信息
global
log 127.0.0.1 local2
daemon
maxconn 256
log 127.0.0.1 local2 info
defaults
log global
mode http
timeout connect 5000ms
timeout client 50000ms
timeout server 50000ms
option dontlognull listen stats :8888
stats enable
stats uri /admin
stats auth admin:1234 frontend oldboy.org
bind 0.0.0.0:80
option httplog
option httpclose
option forwardfor
log global
acl www hdr_reg(host) -i www.oldboy.org
use_backend www.oldboy.org if www backend www.oldboy.org
server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
server 100.1.7.9 100.1.7.9 weight 20 maxconn 300
server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
ha_file
下面是主要程序代码,
#!/use/bin/env python
#_*_ coding:utf_8 _*_
import json,time,os,sys time_now=time.strftime('%Y-%m-%d %H:%M:%S')
time_flag=time.strftime('%Y-%m-%d-%H-%M-%S') if __name__ =='__main__':
"""
主函数,通过判断用户输入执行相应操作
:return:
"""
while True:
print(
'''
---------------------------------------
请输入下列编号进行操作,按q退出:
1:获取haproxy记录
2:增加haproxy记录
3: 删除haproxy记录
----------------------------------------
''')
get_mun = input('请输入操作序号:')
if get_mun == 'q':
exit('bye')
if get_mun.isdigit:
get_mun = int(get_mun)
if get_mun == 1: #如果选择1,则执行get_ha()
read = input("请输入backend:(例如:www.oldboy.org)")
ha_list = get_ha(read)
if len(ha_list)!= 0:
print(ha_list)
else:
print('没有找到相应记录,请检查输入是否正确')
elif get_mun == 2:
add_ha()
elif get_mun == 3:
del_domain = input('请输入想要删除的值:')
del_ha(del_domain)
main()
main函数调用其他几个函数,分别为查询记录,增加记录和删除记录
定义查询函数
def get_ha(get_read):
"""
定义查询函数
:param get_read:用户输入想查询的信息
:return:返回查询结果
"""
get_flags = 0 #设置标识符,当匹配到输入时置为1
get_list = [] #将匹配到的内容放在列表中
with open('ha_file','r',encoding='utf-8') as f:
for line in f.readlines():
line = line.strip() #去掉多余的空格和换行符
if line == 'backend %s'%get_read:
get_flags = 1
elif line.startswith('backend'):
get_flags = 0
elif get_flags == 1 and len(line)!= 0 :
get_list.append(line)
return get_list
get_ha()
定义增加函数
def add_ha():
while True:
add_resource_str = input('请输入想要增加的记录: ')
result_check = check_input(add_resource_str)
if result_check == False:
print('请输入正确格式')
if result_check == True:
add_resource = json.loads(add_resource_str) #取得输入的值
domain_info = add_resource['backend']
server_info = add_resource['record']['server']
weight_info = add_resource['record']['weight']
maxcont_info = add_resource['record']['maxconn']
match_info = ('server {} {} weight {} maxconn {}').format(server_info,server_info,weight_info,maxcont_info)
#match_info 判断信息是否存在,不存在则添加进文件
# print(match_info,type(match_info))
# print(domain_info)
get_match = get_ha(domain_info) #原文件已经存在的记录
# print(get_match[0])
if get_match != []:#域名信息存在
if get_match[0] == match_info:
print('信息已存在,不做更改')
else:
#域名信息存在,但是有更新,f1为原文件,f2为备份文件
with open('ha_file','r',encoding='utf-8') as f1:
all_config = f1.readlines()
match_item = 'backend {}\n'.format(domain_info) #获得更新后的配置信息
#print(match_item)
if str(match_item) in all_config:
update_index = all_config.index(str(match_item))
insert_record_index = int(update_index) +1
all_config.insert(int(insert_record_index),8*' '+match_info+'\n') #将数据插入
with open('ha_new','w',encoding='utf-8') as f2:
f2.writelines(all_config)
os.rename('ha_file','ha_bak%s'%(time_flag))
os.rename('ha_new','ha_file')
else: #原文件不存在相同域名,追加到文件末尾
with open('ha_file','r',encoding='utf-8') as f1,open('ha_new','w',encoding='utf-8') as f2:
all_config = f1.readlines()
str_append = ('''
backend %s
%s
'''%(domain_info,match_info))# 字符串预格式化
all_config.append(str_append)
f2.writelines(all_config)
os.rename('ha_file','ha_bak')
os.rename('ha_new','ha_file')
return
add_ha
定义删除函数
def get_ha(get_read):
"""
定义查询函数
:param get_read:用户输入想查询的信息
:return:返回查询结果
"""
get_flags = 0 #设置标识符,当匹配到输入时置为1
get_list = [] #将匹配到的内容放在列表中
with open('ha_file','r',encoding='utf-8') as f:
for line in f.readlines():
line = line.strip() #去掉多余的空格和换行符
if line == 'backend %s'%get_read:
get_flags = 1
elif line.startswith('backend'):
get_flags = 0
elif get_flags == 1 and len(line)!= 0 :
get_list.append(line)
return get_list
del_ha
由于本次为手动输入记录,对格式有严格的要求,所以定义一个检查输入的函数。实际环境中应该是从其他地方get到格式化好的值。
def check_input(check_dir):
"""
检查输入格式是否正确
:param check_str:
:return:
"""
try:
check = json.loads(check_dir)
domain_info = check['backend']
server_info = check['record']['server']
weight_info = check['record']['weight']
maxcont_info = check['record']['maxconn'] except:
return False
else:
return True
check_input
s13 day3作业的更多相关文章
- Python学习day3作业
days3作业 作业需求 HAproxy配置文件操作 根据用户输入,输出对应的backend下的server信息 可添加backend 和sever信息 可修改backend 和sever信息 可删除 ...
- 老男孩Day3作业:工资管理系统
作业需求: 1.从info.txt文件中读取员工及其工资信息,最后将修改或增加的员工工资信息也写入原info.txt文件. 2.能增查改员工工资 3.增.改员工工资用空格分隔 4.实现退出功能 1)编 ...
- Python3.5 day3作业二:修改haproxy配置文件。
需求: 1.使python具体增删查的功能. haproxy的配置文件. global log 127.0.0.1 local2 daemon maxconn 256 log 127.0.0.1 lo ...
- Python3.5 day3作业一:实现简单的shell sed替换功能
需求: 1.使python具有shell中sed替换功能. #!/usr/bin/env python #_*_conding:utf-8_*_ #sys模块用于传递参数,os模块用于与系统交互. i ...
- python基础:day3作业
修改haproxy配置文件 基本功能:1.获取记录2.添加记录3.删除记录 代码结构:三个函数一个主函数 知识点:1.python简单数据结构的使用:列表.字典等 2.python两个模块的使用:os ...
- Day3作业及默写
1.有变量量name = "aleX leNb" 完成如下操作: 移除 name 变量对应的值两边的空格,并输出处理结果 print(name.strip()) 移除 name 变 ...
- Python 全栈开发:day3 作业与默写
# 1.有变量name = "aleX leNb" 完成如下操作:name = 'aleX leNb'# 1)移除 name 变量对应的值两边的空格,并输出处理结果print(na ...
- day3 作业
文件操作用户很广泛,我们经常对文件进行操作: global log 127.0.0.1 local2 daemon maxconn log 127.0.0.1 local2 info defaults ...
- Day3作业 .
,))::])]): :-])# 3,使用while和for循环分别打印字符串s=’asdfer’中每个元素. # 4,实现一个整数加法计算器:# 如:content = input(‘请输入内容:’ ...
随机推荐
- Tomcat内存问题解决办法
使用Java程序从数据库中查询大量的数据时出现异常:java.lang.OutOfMemoryError: Java heap space 在JVM中如果98%的时间是用于GC且可用的 Heap si ...
- 使用ui给定的字体,通过css引入字体库
@font-face { font-family: 'LCDMonoNormal'; src: url('../../assets/fonts/LCDM2N__.eot'); src: url('.. ...
- Redis缓存接入监控、运维平台CacheCloud
改造RedisConnectionFactory /** * 根据缓存策略的不同,RedisConnectionFactory不同 * 示例是单机模式. * * @return */@Beanpubl ...
- PHP基础知识总结(四) 留言板例子 知识应用
1.留言板显示页面:note.php <?php $host = "127.0.0.1"; $user = "root"; $pwd = "zs ...
- PAT甲级——A1149DangerousGoodsPackaging【25】
When shipping goods with containers, we have to be careful not to pack some incompatible goods into ...
- 利用URL Protocol实现网页调用本地应用程序
http://blog.csdn.net/zssureqh/article/details/25828683
- Visual Studio 2013创建并运行Cocos2d-x工程
| 版权声明:本文为博主原创文章,未经博主允许不得转载. 1.准备: 我们得先把Visual Studio 2013安装好:可以去MSDN官网下载,在安装好 2.安装好vs之后,在cmd(终端)创 ...
- RegionServer Splitting Implementation:regionServer 分裂过程分析
图片: RegionServer Split Process The RegionServer decides locally to split the region, and prepares th ...
- 10个艰难的Java面试题与答案
10个最难回答的Java面试题 这是我收集的10个较难回答的 Java 面试题.这些问题主要来自 Java 核心部分 ,不涉及 Java EE 相关问题.这些问题都是容易在各种 Java 面试中被问到 ...
- 关于JDK,tomcat,eclipse的配置
1.下载安装JDK 在自定义安装路径时,jdk和之后的jre文件夹是属于平行结构,我的安装路径为:D:\jdk\jdk1.6.0_43和D:\jdk\jre6 然后是对环境变量的配置, 计算机→属性→ ...