需求:

1、查
输入:www.oldboy.org
获取当前backend下的所有记录 2、新建
输入:
arg = {
'bakend': 'www.oldboy.org',
'record':{
'server': '100.1.7.9',
'weight': 20,
'maxconn': 30
}
} 3、删除
输入:
arg = {
'bakend': 'www.oldboy.org',
'record':{
'server': '100.1.7.9',
'weight': 20,
'maxconn': 30
}
}
分析:
1、输入是字典模式的字符串,需要把字符串转换为字典,对字典进行处理
2、对文件进行copy,读取,覆盖写操作,还要设置标志,进行区分处理
3、函数的调用 功能查:
def fetch(backend):
#取出backend相关的server信息
result = [] #定义结果列表
with open("haproxy","r",encoding="utf-8") as f: #循环读取文件
flag = False #标记为假
for line in f :
#以backend开头
line = line.strip()
if line.startswith("backend") and line == "backend %s" %backend:
flag = True #读取到backend开头的信息,标记为真
continue #直接返回到for语句
#如果遇到下一个backend开头的语句,直接break跳出for语句,因为数据拿完了
if flag and line.startswith("backend"):
flag = False
break
#server信息添加到result列表
if flag and line.strip():
result.append(line)
return result
实现代码:
import shutil
import json def list_function():
print("Please choice the ID of a action.".center(50,"#"))# 50g个字符,提示在中间,不够的#补足
print("【1】.Fetch haproxy backend infomation.")
print("【2】.Add haproxy backend infomation.")
print("【3】.Delete haproxy backend infomation.")
print("【q】.Delete haproxy backend infomation.")
def fetch(backend):
#取出backend相关的server信息
result = [] #定义结果列表
with open("haproxy","r",encoding="utf-8") as f: #循环读取文件
flag = False #标记为假
for line in f :
#以backend开头
line = line.strip()
if line.startswith("backend") and line == "backend %s" %backend:
flag = True #读取到backend开头的信息,标记为真
continue #直接返回到for语句
#如果遇到下一个backend开头的语句,直接break跳出for语句,因为数据拿完了
if flag and line.startswith("backend"):
flag = False
break
#server信息添加到result列表
if flag and line.strip():
result.append(line)
return result def writer(backend,record_list):
with open("haproxy","r") as old,open("haproxy_new","w") as new:
flag = False
for line in old:
if line == "backend %s\n" %backend:
flag = True
new.write(line)
for new_line in record_list:
new.write(""*4 + new_line + "\n")
continue
if flag and line.strip().startswith("backend"):
flag = False
new.write(line)
continue #跳到下一次循环,防止backend写两次
if line.strip() and not flag:
new.write(line) def add(backend, record):
global change_flag
record_list = fetch(backend) #查找是否存在backend
if not record_list and record_list != []: #backend不存在同时record_list是空列表
with open('haproxy','r') as old, open("haproxy_new",'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存在
if record in record_list:
print("Record already in it,Nothing to do!")
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:
print("Not match the backend,no need delete!".center(50,"#"))
else:
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 math 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 operate(action):
global change_flag
if action == "fetch":
backend_info = input("Input backend info:")
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 = input("Input backend info(dict):") # 输入的是字符串,
backend_record_dict = eval(backend_record)
backend = backend_record_dict['backend']
record = backend_record_dict['record']
record = "server %s %s weight %s maxconn %s" % (record['server'], record['server'],
record['weight'], record['maxconn'])
if action == "add":
add(backend,record)
elif action == "delete":
delete(backend,record)
if change_flag is True: #文件有修改,才进行文件更新
shutil.copy("haproxy","haproxy_old")
shutil.copy("haproxy_new","haproxy")
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":
action = "add"
elif input_info == "3":
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. s12-day03-work01 python修改haproxy配置文件(初级版本)

    #!/usr/local/env python3 ''' Author:@南非波波 Blog:http://www.cnblogs.com/songqingbo/ E-mail:qingbo.song ...

  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配置文件

    需要掌握的知识: 1.函数 2.文件处理 3.tag的用法 4.程序的解耦 需求: 1:查询 2:添加 3:删除 4:修改 5:退出 haproxy.conf 配置文件内容: global log 1 ...

  4. 用python修改haproxy配置文件

    需求: 当用户输入域名的时候,显示出来下面的记录 当用户需要输入添加纪录的时候,添加到你需要的那个域名下面 global log 127.0.0.1 local2 daemon maxconn 256 ...

  5. Python3学习之路~2.10 修改haproxy配置文件

    需求: .查 输入:www.oldboy.org 获取当前backend下的所有记录 .新建 输入: arg = { 'bakend': 'www.oldboy.org', 'record':{ 's ...

  6. 5.修改haproxy配置文件

    需求: 1.查 输入:www.oldboy.org 获取当前backend下的所有记录 2.新建 输入: arg = { 'backend': 'www.oldboy.org', 'record':{ ...

  7. python基础-4.1 open 打开文件练习:修改haproxy配置文件

    1.如何在线上环境优雅的修改配置文件? 配置文件名称ini global log 127.0.0.1 local2 daemon maxconn 256 log 127.0.0.1 local2 in ...

  8. 作业---修改haproxy配置文件

    #查询 f=open("C:\\aaaaaaaaaaaaa\\haproxy.txt", "r", encoding="utf-8") ha ...

  9. python编辑修改haproxy配置文件--文件基础操作

    一.需求分析 有查询,删除,添加的功能 查询功能:查询则打印查询内容,如果不存在也要打印相应的信息 删除功能:查询到要删除内容则删除,打印信息. 添加功能:同上. 二.流程图 三.代码实现 本程序主要 ...

随机推荐

  1. [原创]c# 岛2 小辅助~~~ 钓鱼 连击

  2. 使用apt-get安装相关的软件时,不能Fetch,现在更新为国内的源!

    我使用的是中国科技大学的树莓派的软件源,测试可以使用(更新时间:2018年7月15日) deb http://mirrors.ustc.edu.cn/raspbian/raspbian/ jessie ...

  3. (三)ajax请求不同源之cors跨域

    一.基本原理 CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)它允许浏览器向跨源服务器,发出 XMLHttpReque ...

  4. BZOJ.4009.[HNOI2015]接水果(整体二分 扫描线)

    LOJ BZOJ 洛谷 又是一个三OJ rank1!=w= \(Description\) (还是感觉,为啥非要出那种题目背景啊=-=直接说不好么) 给定一棵树和一个路径集合(每条路径有一个权值).\ ...

  5. fflush()函数:更新缓冲区

    fflush()的作用是用来刷新缓冲区: fflush(stdin)刷新标准输入缓冲区,把输入缓冲区里的东西丢弃:stdin是standard input的缩写,即标准输入,一般是指键盘:标准输入缓冲 ...

  6. 潭州课堂25班:Ph201805201 tornado 项目 第五课 增加用户系统-用户中心(课堂笔记)

    tornado 相关说明 在 users 表中创建记录,做测试 在项目根目录下创建 test.py # -*- coding: utf-8 -*- # 斌彬电脑 # @Time : 2019/2/27 ...

  7. # Do—Now——团队冲刺博客_总结篇

    Do-Now--团队冲刺博客_总结篇 目录 博客链接 作者 1. 第一篇(领航篇) @仇夏 2. 第二篇 @侯泽洋 3. 第三篇 @仇夏 4. 第四篇 @周亚杰 5. 第五篇 @唐才铭 6. 第六篇 ...

  8. css 网格布局简单应用

    将属性 display 值设为 grid 或 inline-grid 就创建了一个网格容器,所有容器直接子结点自动成为网格项目. grid :网格项目按行排列,网格项目占用整个容器的宽度. inlin ...

  9. C#中异步调用示例与详解

    using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServi ...

  10. ECMA Script 6_必须要知道的基础

    ES6 为了保持兼容性,var 命令和 function 命令声明的全局变量,依旧是顶层对象的属性: 另一方面规定,let 命令.const 命令.class 命令声明的全局变量,不属于 window ...