Python学习day3作业
days3作业
作业需求
HAproxy配置文件操作
- 根据用户输入,输出对应的backend下的server信息
- 可添加backend 和sever信息
- 可修改backend 和sever信息
- 可删除backend 和sever信息
- 操作配置文件前进行备份
- 添加server信息时,如果ip已经存在则修改;如果backend不存在则创建;若信息与已有信息重复则不操作
- [x] 博客
- [x] 查询backend下的server信息
- [x] 添加backend和server信息
- [ ] 修改backend 和sever信息
- [x] 删除backend和server信息
博客地址
基本流程图
程序代码
#!/usr/bin/env python
# _*_coding:utf-8_*_
'''
* Created on 2016/11/7 21:24.
* @author: Chinge_Yang.
'''
import shutil
import json
def list_function():
print("Please choice the ID of a action.".center(50, "#"))
print("【1】.Fetch haproxy.cfg backend infomation.")
print("【2】.Add haproxy.cfg backend infomation.")
print("【3】.Delete haproxy.cfg backend infomation.")
print("End".center(50, "#"))
def fetch(backend):
# 取出backend相关server信息
result = [] # 定义结果列表
with open("haproxy.cfg", "r", encoding="utf-8") as f: # 循环读取文件
flag = False # 标记为假
for line in f:
# 以backend开头
line = line.strip()
if line.startswith("backend") and line == "backend " + backend:
flag = True # 读取到backend开头的信息,标记为真
continue
# 下一个backend开头
if flag and line.strip().startswith("backend"):
flag = False
break
# server信息添加到result列表
if flag and line.strip():
result.append(line.strip())
return result
def writer(backend, record_list):
with open("haproxy.cfg", "r") as old, open("new.cfg", "w") as new:
flag = False
for line in old:
if line.strip().startswith('backend') and line.strip() == "backend " + backend:
flag = True
new.write(line)
for new_line in record_list:
new.write(" " * 4 + new_line + "\n")
continue # 跳到下一次循环,避免下一个backend写二次
if flag and line.strip().startswith("backend"): # 下一个backend
flag = False
new.write(line)
continue # 退出此循环,避免server信息二次写入
if line.strip() and not flag:
new.write(line)
def add(backend, record):
global change_flag
record_list = fetch(backend) # 查找是否存在记录
if not record_list: # backend不存在, record不存在
with open('haproxy.cfg', 'r') as old, open('new.cfg', 'w') as new:
for line in old:
new.write(line)
# 添加新记录
new.write("\nbackend " + backend + "\n")
new.write(" " * 4 + record + "\n")
print("\033[32;1mAdd done\033[0m")
change_flag = True
else: # backend存在,record存在
if record in record_list:
print("\033[31;1mRecord already in it,Nothing to do!\033[0m")
change_flag = False
else: # backend存在,record不存在
record_list.append(record)
writer(backend, record_list)
print("\033[32;1mAdd done\033[0m")
change_flag = True
def delete(backend, record):
global change_flag
record_list = fetch(backend) # 查找是否存在记录
if not record_list: # backend不存在, record不存在
print("Not match the backend,no need delete!".center(50, "#"))
change_flag = False
else: # backend存在,record存在
if record in record_list:
record_list.remove(record) # 移除元素
writer(backend, record_list) # 写入
print("\033[31;1mDelete done\033[0m")
change_flag = True
else: # backend存在,record不存在
print("Only match backend,no need delete!".center(50, "#"))
change_flag = False
return change_flag
def output(servers):
# 输出指定backend的server信息
print("Match the server info:".center(50, "#"))
for server in servers:
print("\033[32;1m%s\033[0m" % server)
print("#".center(50, "#"))
def input_json():
# 判断输入,要求为json格式
continue_flag = False
while continue_flag is not True:
backend_record = input("Input backend info(json):").strip()
try:
backend_record_dict = json.loads(backend_record)
except Exception as e:
print("\033[31;1mInput not a json data type!\033[0m")
continue
continue_flag = True
return backend_record_dict
def operate(action):
global change_flag
if action == "fetch":
backend_info = input("Input backend info:").strip()
result = fetch(backend_info) # 取出backend信息
if result:
output(result) # 输出获取到的server信息
else:
print("\033[31;1mNot a match is found!\033[0m")
elif action is None:
print("\033[31;1mNothing to do!\033[0m")
else:
backend_record_dict = input_json() # 要求输入json格式
for key in backend_record_dict:
backend = key
record = backend_record_dict[key]
if action == "add":
add(backend, record)
elif action == "delete":
delete(backend, record)
if change_flag is True: # 文件有修改,才进行文件更新
# 将操作结果生效
shutil.copy("haproxy.cfg", "old.cfg")
shutil.copy("new.cfg", "haproxy.cfg")
result = fetch(backend)
output(result) # 输出获取到的server信息
def judge_input():
# 判断输入功能编号,执行相应步骤
input_info = input("Your input number:").strip()
if input_info == "1": # 查询指定backend记录
action = "fetch"
elif input_info == "2": # 添加backend记录
action = "add"
elif input_info == "3": # 删除backend记录
action = "delete"
elif input_info == "q" or input_info == "quit":
exit("Bye,thanks!".center(50, "#"))
else:
print("\033[31;1mInput error!\033[0m")
action = None
return action
def main():
exit_flag = False
while exit_flag is not True:
global change_flag
change_flag = False
list_function()
action = judge_input()
operate(action)
if __name__ == '__main__':
main()
HAproxy配置文件操作
1.程序说明
实现功能如下
- [x] 查询backend下的server信息
- [x] 添加backend和server信息
- [ ] 修改backend 和sever信息
- [x] 删除backend和server信息
2.程序测试帐号
3.程序测试
cat haproxy.cfg
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 51cto.com
bind 0.0.0.0:80
option httplog
option httpclose
option forwardfor
log global
acl www hdr_reg(host) -i test01.example.com
use_backend test01.example.com if www
backend test01.example.com
server 100.1.7.10 100.1.7.10 weight 20 maxconn 3000
backend test.com
server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000
server 100.1.7.66 100.1.7.66 weight 20 maxconn 3000
server 100.1.7.27 100.1.7.27 weight 20 maxconn 3000
server 100.1.7.13 100.1.7.13 weight 20 maxconn 3000
backend www.test.com
server 100.1.7.13 100.1.7.13 weight 20 maxconn 3000
执行结果:
########Please choice the ID of a action.#########
【1】.Fetch haproxy.cfg backend infomation.
【2】.Add haproxy.cfg backend infomation.
【3】.Delete haproxy.cfg backend infomation.
#######################End########################
Your input number:1
Input backend info:test.com
##############Match the server info:##############
server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000
server 100.1.7.66 100.1.7.66 weight 20 maxconn 3000
server 100.1.7.27 100.1.7.27 weight 20 maxconn 3000
##################################################
########Please choice the ID of a action.#########
【1】.Fetch haproxy.cfg backend infomation.
【2】.Add haproxy.cfg backend infomation.
【3】.Delete haproxy.cfg backend infomation.
#######################End########################
Your input number:2
Input backend info(json):{"test.com":"testtest.com"}
Add done
##############Match the server info:##############
server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000
server 100.1.7.66 100.1.7.66 weight 20 maxconn 3000
server 100.1.7.27 100.1.7.27 weight 20 maxconn 3000
testtest.com
##################################################
########Please choice the ID of a action.#########
【1】.Fetch haproxy.cfg backend infomation.
【2】.Add haproxy.cfg backend infomation.
【3】.Delete haproxy.cfg backend infomation.
#######################End########################
Your input number:1
Input backend info:test.com
##############Match the server info:##############
server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000
server 100.1.7.66 100.1.7.66 weight 20 maxconn 3000
server 100.1.7.27 100.1.7.27 weight 20 maxconn 3000
testtest.com
##################################################
########Please choice the ID of a action.#########
【1】.Fetch haproxy.cfg backend infomation.
【2】.Add haproxy.cfg backend infomation.
【3】.Delete haproxy.cfg backend infomation.
#######################End########################
Your input number:3
Input backend info(json):{"test.com":"testtest.com"}
Delete done
##############Match the server info:##############
server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000
server 100.1.7.66 100.1.7.66 weight 20 maxconn 3000
server 100.1.7.27 100.1.7.27 weight 20 maxconn 3000
##################################################
########Please choice the ID of a action.#########
【1】.Fetch haproxy.cfg backend infomation.
【2】.Add haproxy.cfg backend infomation.
【3】.Delete haproxy.cfg backend infomation.
#######################End########################
Your input number:4
Input error!
Nothing to do!
########Please choice the ID of a action.#########
【1】.Fetch haproxy.cfg backend infomation.
【2】.Add haproxy.cfg backend infomation.
【3】.Delete haproxy.cfg backend infomation.
#######################End########################
Your input number:3
Input backend info(json):d
Input not a json data type!
Input backend info(json):{"test01.example.com":"server 100.1.7.27 100.1.7.27 weight 20 maxconn 3000"}
########Only match backend,no need delete!########
########Please choice the ID of a action.#########
【1】.Fetch haproxy.cfg backend infomation.
【2】.Add haproxy.cfg backend infomation.
【3】.Delete haproxy.cfg backend infomation.
#######################End########################
Your input number:q
###################Bye,thanks!####################
Process finished with exit code 1
Python学习day3作业的更多相关文章
- Python学习day5作业
目录 Python学习day5作业 ATM和购物商城 1. 程序说明 2. 基本流程图 3. 程序测试帐号 4. 程序结构: 5. 程序测试 title: Python学习day5作业 tags: p ...
- python学习-day3
今天是第三天学习,加油! 第一部分 集合 一.集合 1.什么是集合以及特性? 特性:无序的,不重复的序列,可嵌套. 2.创建集合 方法一:创建空集合 s1 = set() print(type(s1) ...
- python学习day3
目录: 1.集合set 2.计数器 3.有序字典 4.默认字典 5.可命名元组 6.队列 7.深浅拷贝 8.函数 9.lambda表达式 10.内置函数 一.集合set set是一个无序且不重复的元素 ...
- 老男孩python学习之作业一购物小程序
想学编程由来已久 始终没有个结果,痛心不已 如今再次捡起来,望不负期望,不负岁月 ......一万字的废话...... 先介绍一下我的自学课程吧 "路飞学城"的<python ...
- python学习Day3 变量、格式化输出、注释、基本数据类型、运算符
今天复习内容(7项) 1.语言的分类 -- 机器语言:直接编写0,1指令,直接能被硬件执行 -- 汇编语言:编写助记符(与指令的对应关系),找到对应的指令直接交给硬件执行 -- 高级语言:编写人能识别 ...
- python学习 day3 (3月4日)---字符串
字符串: 下标(索引) 切片[起始:终止] 步长[起始:终止:1] 或者-1 从后往前 -1 -2 -3 15个专属方法: 1-6 : 格式:大小写 , 居中(6) s.capitalize() s ...
- python基础:day3作业
修改haproxy配置文件 基本功能:1.获取记录2.添加记录3.删除记录 代码结构:三个函数一个主函数 知识点:1.python简单数据结构的使用:列表.字典等 2.python两个模块的使用:os ...
- 老男孩python学习之作业二---三级菜单
因为之前花力气完成了购物小程序的作业 现在做这个三级菜单简直是so easy!! 1.显示省级菜单 2.交互,提示用户输入要查看的省份(退出e) 2.1.用户正确输入列表中的省份 3.显示市级菜单 3 ...
- python学习day3 编程语言分类 变量 格式化输出
1.编程语言分类 机器语言:直接使用二进制指令直接编写程序,直接操作计算机硬件,必须考虑硬件细节 汇编语言:使用英文标签代替二进制指令去编写程序,直接操作计算机硬件,必须考虑硬件细节对,不过相比机器语 ...
随机推荐
- C#无限极分类树-创建-排序-读取 用Asp.Net Core+EF实现之方法二:加入缓存机制
在上一篇文章中我用递归方法实现了管理菜单,在上一节我也提到要考虑用缓存,也算是学习一下.Net Core的缓存机制. 关于.Net Core的缓存,官方有三种实现: 1.In Memory Cachi ...
- 绿色简单的学校登录html页面
效果预览:http://hovertree.com/texiao/css/22/ 代码如下: <!DOCTYPE html> <html> <head> <m ...
- C++_系列自学课程_第_7_课_数组_《C++ Primer 第四版》
说到数组,大家应该都很熟悉,在C.Pascal.Java等语言中,都有数组的概念.在C++中也提供了对数组的支持.数组简单来说就是一堆相同 数据类型对象的集合. 这里要把握住两个要点: 相同的数据类型 ...
- C标准头文件<signal.h>
信号即异常,或者理解为中断,一个进程接收到一个信号,如果没有处理机制,就会按照默认的处理方式进行处理,而默认的处理方式通常是终止当前进程或忽略该信号.当然,程序也可以编写相应的处理信号的函数,一旦接收 ...
- java Byte[] to String(hex)
1. 字节数组转换成16进制字符展示 2.代码 package com.goodfan; public class ByteArrayToString { private static char[] ...
- 从零开始学 Java - CentOS 下安装 Tomcat
生活以痛吻我,我仍报之以歌 昨天晚上看到那个冯大辉老师的微信公众号,「小道消息」上的一篇文章,<生活以痛吻我,我仍报之以歌>.知乎一篇匿名回答,主题为<冯大辉到底是不是技术大牛,一个 ...
- Lind.DDD.Manager里的3,7,15,31,63,127,255,511,1023,2047
回到目录 进制 我是一个程序猿,我喜欢简单的数字,十进制如何,数字太多,有10种数字组成,但由于它广为人知,所有使用最为广泛,人们的惯性思维培养了十进制,并说它是最容易被计算的数字,事实上,在计算机里 ...
- [JS]笔记14之事件委托
-->什么是事件委托-->事件委托原理-->事件委托优点-->事件源 / 目标源 一.什么是事件委托 通俗的讲,onclick,onmouseover,onmouseout等这 ...
- ASP.NET MVC之路由深究
MVC的强大之处之一当然是路由,这是几年前一位牛人给我说过的话,本人深感认同.今天就再次探究. 首先新建一个空的MVC项目,我们会发现在RouteConfig类中存在一个默认的路由配置,通常我会在这里 ...
- SharePoint 2013 工作流之使用Visio设计篇
SharePoint 2013增强了工作流,不仅仅基于WorkFlow Foundation 4.0了,设计方式也不仅仅是Designer,还包括Visio中设计,下面我们就一个简单的例子,介绍下. ...