首页 > 代码库 > PYTHON学习第一模块 Haproxy配置操作
PYTHON学习第一模块 Haproxy配置操作
购物车模拟
需求:
- 根据用户输入输出对应的backend下的
- server信息可添加backend 和
- sever信息可删除backend 和sever信息
- 添加server信息时,信息与已有信息重复则不操作
说明:
- python版本为3.6
- 增删查的结果均在haproxy.conf内可以验证
haproxy.conf配置文件内容:
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 weight 20 maxconn 3000 backend www.qq.com server 100.1.7.10 weight 20 maxconn 3000 backend www.cnblog.com server 100.1.7.14 weight 20 maxconn 3000
代码:
# /usr/bin/env python # -*- coding: utf-8 -*- # AUTHOR:Fio import os import json arg = { ‘backend‘: ‘www.yahoo.com‘, ‘record‘: { ‘ip‘: ‘100.1.7.13‘, ‘weight‘: ‘20‘, ‘maxconn‘: ‘3000‘ } } def select_info(url): flag = False with open(‘./haproxy.conf‘, ‘r‘) as conf: for line in conf: if line.strip().startswith("backend %s" % url): flag = True continue if flag: record_info = line.strip() flag = False print(record_info) def insert_info(info): server_info = eval(info) url = server_info[‘backend‘] ip = server_info[‘record‘][‘ip‘] weight = server_info[‘record‘][‘weight‘] maxconn = server_info[‘record‘][‘maxconn‘] flag = False with open(‘./haproxy.conf‘, ‘r‘) as conf1: for line in conf1: if line.strip().startswith(‘backend %s‘ % url): print("配置已存在") flag = False break else: flag = True continue if flag: with open(‘./haproxy.conf‘, ‘a‘) as conf2: conf2.write(‘backend ‘ + url + ‘\n‘) conf2.write(‘ server %s weight %s maxconn %s\n‘ % (ip, weight, maxconn)) print("配置%s插入成功" % url) def delete_info(url): flag = False with open(‘./haproxy.conf‘, ‘r+‘) as conf1: with open(‘./haproxy_tmp.conf‘, ‘w‘) as conf2: for line1 in conf1: if line1.strip().startswith(‘backend %s‘ % url): conf2.write("") flag = True continue elif flag and line1.strip().startswith(‘server‘): conf2.write("") flag = False continue else: conf2.write(line1) continue os.remove(‘./haproxy.conf‘) os.rename(‘./haproxy_tmp.conf‘, ‘./haproxy.conf‘) print(‘backend %s内容已删除‘ % url) if __name__ == "__main__": print(‘‘‘ ############################### # 请选择操作方法: # 1. 查询 # 2. 插入 # 3. 删除 ############################### ‘‘‘) order_num = input("选择的序号:") if order_num == ‘1‘: URL = input("请选择要查询的域名:") select_info(URL) elif order_num == ‘2‘: INFO = input(‘‘‘请输入完整的配置, 示例格式({ ‘backend‘: ‘www.yahoo.com‘, ‘record‘: { ‘ip‘: ‘100.1.7.13‘, ‘weight‘: ‘20‘, ‘maxconn‘: ‘3000‘ }}) :‘‘‘) insert_info(INFO) elif order_num == ‘3‘: URL = input("请输入要删除的域名配置:") delete_info(URL) else: print("请输入正确的序号!")
PYTHON学习第一模块 Haproxy配置操作
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。