Python3.5 day3作业二:修改haproxy配置文件。

需求:

1.使python具体增删查的功能。

haproxy的配置文件。

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
import  os,re,sys
from collections import defaultdict,OrderedDict
conf = "haproxy.cfg"
conf_new = "haproxy.cfg.new"
backend_list = []
server_dict= {}
show_dict = {}
backend_name_dict = {}
server_info= []
server_flag = False                                                     ###初始化server判断标志位###
with open(conf,‘r‘) as ha:                                             ###打开haproxy配置文件###
    for line in ha:
        line = line.strip(‘\n‘)
        if re.match(‘backend‘,line):                                    ###匹配配置文件以backend开头的行###
            backend_name = re.split(‘\s+‘,line)[1]
            backend_list.append(backend_name)
            server_info1 = []
            server_flag = True                                           ###赋值标志位为真,用来与server关联###
        elif server_flag and re.match(‘\s+server‘,line):               ###匹配配置文件以server开头的行###
            server_info = re.split(‘\s+‘,line)
            server_info.remove(‘‘)
            server_info1.append(server_info)
            server_dict[‘server‘] = server_info[1]
            server_dict[‘weight‘] = server_info[4]
            server_dict[‘maxconn‘] = server_info[5]
            backend_name_dict[backend_name] = "name"
            backend_name_dict[backend_name] = server_info1
        else:
            server_flag = False

#循环
options_list = ["1.查询backend","2.删除backend","3.新增backend","5.退出"]
while True:
      for i in options_list:
        print(i)
      find = (input("\033[94m请选择操作条目序号:\033[0m"))
      if find.isdigit():
            find = int((find))
            #1是查询
            if find == 1:
               for i, ele in enumerate(backend_list):
                   print(i, ele)
               find1 = input("请输入您要查询的backend的序号:")
               find1 = int(find1)
               for j in range(1):
                   print("==========%s============" %backend_list[find1])
                   for i in backend_name_dict[backend_list[find1]]:
                      print("server %s weigt %s maxconn %s" %(i[1],i[3],i[5]))
            #2是删除
            elif find == 2:
               for i, ele in enumerate(backend_list):
                       print(i, ele)
               find3 = int(input("请选择您要删除backend的序号:"))
               server_show = []
               for i, ele in enumerate(backend_name_dict[backend_list[find3]]):
                               server_show.append("server %s weight %s maxconn %s" % (ele[1], ele[3], ele[5]))
                               print(i, "server %s weight %s maxconn %s" % (ele[1], ele[3], ele[5]))
                               server_show1= str(server_show[0])
                               print(server_show1)
                               f = open(conf, "r")
                               f1 = open(conf_new, "a+")
                               for i in f:
                                   if server_show1 in i:
                                       i = i.replace(server_show1, "")
                                   f1.write(i)
                                   f1.flush()
                               f.close()
                               f1.close()
                               os.remove(conf)
                               os.rename(conf_new, conf)
                               backend_list1 = []
                               backend_list1.append("backend %s" %(backend_list[find3]))
                               backend_list2 = str(backend_list1[0])
                               f = open(conf, "r")
                               f1 = open(conf_new, "a+")
                               for i in f:
                                   if backend_list2 in i:
                                       i = i.replace(backend_list2, "")
                                   f1.write(i)
                                   f1.flush()
                               f.close()
                               f1.close()
                               os.remove(conf)
                               os.rename(conf_new, conf)
                               print("删除成功!!!")
            #3是增加
            elif find == 3:
                   arg = []
                   backend_name1 = []
                   backend_list3 = []
                   input_back = input("\033[94m请输入backend(www.orgboy.org):\033[0m")
                   arg.append("backend %s" %input_back)
                   input_server = input("\033[94m请输入server(127.0.0.1):\033[0m")
                   input_weight = input("\033[94m请输入weight(20):\033[0m")
                   # arg["weight"] = input_weight
                   input_maxconn = input("\033[94m请输入maxconn(3000):\033[0m")
                   arg.append("        server %s weight %s maxconn %s" %(input_server,input_weight,input_maxconn))
                   backend_name1 = str(arg[0])
                   f = open(conf, "a+")
                   f.write("%s \n" %backend_name1)
                   f.flush()
                   f.close()
                   backend_list3 = arg[1]
                   backend_list3 = str(backend_list3)
                   f = open(conf, "a+")
                   f.write("%s \n" %backend_list3)
                   f.close()
                   print("添加成功!!!")
            #5是退出
            elif find == 5:
               exit()
      else:
          print("\033[91m请输入正确的序号\033[0m")
          continue
时间: 2024-08-15 08:55:59

Python3.5 day3作业二:修改haproxy配置文件。的相关文章

Python小程序—修改haproxy配置文件

程序2:修改haproxy配置文件  需求: 1 1.查 2 输入:www.oldboy.org 3 获取当前backend下的所有记录 4 5 2.新建 6 输入: 7 arg = { 8 'bakend': 'www.oldboy.org', 9 'record':{ 10 'server': '100.1.7.9', 11 'weight': 20, 12 'maxconn': 30 13 } 14 } 15 16 3.删除 17 输入: 18 arg = { 19 'bakend': '

修改haproxy配置文件

HAproxy配置文件操作: 1. 根据用户输入输出对应的backend下的server信息 2. 可添加backend 和sever信息,如果存在则不添加,不修改 4. 可删除backend 和sever信息 5. 首先选择要进入哪种模式(查询,增加,删除),按q退出整个操作,在某种模式内时按b退出重新选择,不退出则 一直处于某种模式内 #Auther:He Jianhan #查def hanshu(names,fliens): print(fliens[names].rstrip()) if

用python修改haproxy配置文件

需求: 当用户输入域名的时候,显示出来下面的记录 当用户需要输入添加纪录的时候,添加到你需要的那个域名下面 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 liste

Part1 - 修改haproxy配置文件

README: 查看.添加.修改.删除分别是用不同函数实现, 运行程序时,有选择列表,并且每项功能都有example提示 流程图: 代码: #!/usr/bin/env python # coding:utf8 import sys import os import shutil import time import re import json if os.path.exists('tab.py'): import tab class handleHaproxyConf(object): "s

Python-Day5修改haproxy配置文件

需求: 1.查 输入:www.oldboy.org 获取当前backend下的所有记录 2.新建 输入: {'backend': 'www.oldboy','record': {'server': '100.1.7.9','weight': 20,'maxconn': 30}} arg = { 'backend': 'www.oldboy.org', 'record':{ 'server': '100.1.7.9', 'weight': 20, 'maxconn': 30 } } 3.删除 输入

Python3.5 day3作业一:实现简单的shell sed替换功能

需求: 1.使python具有shell中sed替换功能. #!/usr/bin/env python #_*_conding:utf-8_*_ #sys模块用于传递参数,os模块用于与系统交互. import sys,os old_file = sys.argv[1] new_file = sys.argv[2] file_path = sys.argv[3] f = open(file_path,"r") f1 = open("back","a+&qu

Registrator+Consul+Consul-template+HaProxy实现动态修改Haproty配置文件

实现需求: 用Haproxy做负载均衡,手动方式在配置文件中添加或删除节点服务器信息,比较麻烦. 通过Registrator收集需要注册到Consul作为Haproxy节点服务器的信息,然后注册到Consul key/value. Consul-template去Consul key/value中读取信息,然后自动修改Haproxy配置文件,并重载Haproxy.不需要修改haproxy.cfg. 集群环境: Postil:Mesos集群搭建过程此处省略 关闭selinux和防火墙 setenf

python之haproxy配置文件操作(第三天)

作业: 对haproxy配置文件进行操作 要求: 对haproxy配置文件中backend下的server实现增删改查的功能 一.这个程序有二个版本 1. python2.7版本见haproxy_python27.py 2. python3.4版本见haproxy_python34.py 二.具体实现了如下功能: 1.输入1,进入backend菜单,查询server信息 2.输入2,进入backend菜单,添加server条目 3.输入3,进入backend菜单,选择server条目,进入修改环

作业:老板现在给你任务,公司有haproxy配置文件,希望通过python程序可以对ha配置文件进行增删改

1 # 老板现在给你任务,公司有haproxy配置文件,希望通过python程序可以对ha配置文件进行增删改 2 #分析:对文件进行增删改,首先需要找到需要修改文件的位置,即必须先把文件读取出来,找到对应 3 #位置,进行内容的修改,增加和删除: 4 import json,os #json模块用于将用户输入的字符串转换为字典 5 6 #首先定义fetch函数,同时传入指定参数backend,用来将修改的地方找出来 7 def fetch(backend): 8 flag=False #定义fl