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(‘请输入内容:’ ...
随机推荐
- 分布式存储Ceph之PG状态详解
https://www.jianshu.com/p/36c2d5682d87 1. PG介绍 继上次分享的<Ceph介绍及原理架构分享>,这次主要来分享Ceph中的PG各种状态详解,PG是 ...
- AcWing 225. 矩阵幂求和 (矩阵快速幂+分治)打卡
题目:https://www.acwing.com/problem/content/227/ 题意:给你n,k,m,然后输入一个n阶矩阵A,让你求 S=A+A^2+A^3.+......+A^k 思 ...
- 优雅的SpringMVC和Restful
一.前言 1.前段时间一直在写微信小程序的请求,终于把客户端的请求弄好了,可是服务端呢,该怎么写,纠结了半天,用servlet暂时写好了一个:http://www.cnblogs.com/JJDJJ/ ...
- django中初学常犯错误之梳理
一,关于setting设置,1,两个INSRALLEN_APPS,需要将新建的app添加进去 2,需要再setting将html的路径拼接起来 二,urls.py 设置,from app名 impor ...
- Jquery 实现回车键触发功能
keyup,上抬键盘 .$(function(){ 方法一: $(document).keyup(function(event){ if(event.keyCode ==13){ alert(&quo ...
- cs224d 作业 problem set2 (一) 用tensorflow纯手写实现sofmax 函数,线性判别分析,命名实体识别
Hi Dear Today we will use tensorflow to implement the softmax regression and linear classifier algor ...
- 运维 07 Linux系统基础优化及常用命令
Linux系统基础优化及常用命令 Linux基础系统优化 引言没有,只有一张图. Linux的网络功能相当强悍,一时之间我们无法了解所有的网络命令,在配置服务器基础环境时,先了解下网络参数设定命令 ...
- jpql简单l查询
JPQL全称Java Persistence Query Language package com.ytkj.entity; import javax.persistence.*; import ja ...
- Django框架(十六)—— cookie和session组件
目录 cookie和session组件 一.cookie 1.cookie的由来 2.什么是cookie 3.cookie的原理 4.cookie的覆盖 5.在浏览器中查看cookie 6.cooki ...
- PHP数组循环遍历的几种方式
PHP数组循环遍历 1.for循环 <?php //语法 for (init counter; test counter; increment counter) { code to be exe ...