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作业的更多相关文章

  1. Python学习day3作业

    days3作业 作业需求 HAproxy配置文件操作 根据用户输入,输出对应的backend下的server信息 可添加backend 和sever信息 可修改backend 和sever信息 可删除 ...

  2. 老男孩Day3作业:工资管理系统

    作业需求: 1.从info.txt文件中读取员工及其工资信息,最后将修改或增加的员工工资信息也写入原info.txt文件. 2.能增查改员工工资 3.增.改员工工资用空格分隔 4.实现退出功能 1)编 ...

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

    需求: 1.使python具体增删查的功能. haproxy的配置文件. global log 127.0.0.1 local2 daemon maxconn 256 log 127.0.0.1 lo ...

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

    需求: 1.使python具有shell中sed替换功能. #!/usr/bin/env python #_*_conding:utf-8_*_ #sys模块用于传递参数,os模块用于与系统交互. i ...

  5. python基础:day3作业

    修改haproxy配置文件 基本功能:1.获取记录2.添加记录3.删除记录 代码结构:三个函数一个主函数 知识点:1.python简单数据结构的使用:列表.字典等 2.python两个模块的使用:os ...

  6. Day3作业及默写

    1.有变量量name = "aleX leNb" 完成如下操作: 移除 name 变量对应的值两边的空格,并输出处理结果 print(name.strip()) 移除 name 变 ...

  7. Python 全栈开发:day3 作业与默写

    # 1.有变量name = "aleX leNb" 完成如下操作:name = 'aleX leNb'# 1)移除 name 变量对应的值两边的空格,并输出处理结果print(na ...

  8. day3 作业

    文件操作用户很广泛,我们经常对文件进行操作: global log 127.0.0.1 local2 daemon maxconn log 127.0.0.1 local2 info defaults ...

  9. Day3作业 .

    ,))::])]): :-])# 3,使用while和for循环分别打印字符串s=’asdfer’中每个元素. # 4,实现一个整数加法计算器:# 如:content = input(‘请输入内容:’ ...

随机推荐

  1. 【LeetCode 35】搜索插入位置

    题目链接 [题解] 还是那句话,想知道l或者r所在的数字的含义 就想想它最后一次执行的时候在干什么就行. [代码] class Solution { public: int searchInsert( ...

  2. Python基础教程(011)--程序开发中的错误及原因

    前言 排查代码开发中的错误 内容 1,编写的程序不能正常执行,或者执行的结果不是我们期望的 2,俗称bug,是程序开发常见的,初学常见的原因有 手误 对已经学习的知识点理解不足 对语音还有需要学习和提 ...

  3. 【已转移】【缓存与性能优化】一篇文章搞掂:Redis

    本文篇幅较长,建议合理利用右上角目录进行查看(如果没有目录请刷新). 一.什么是Redis 全称: Remote Dictionary Server 远程字典服务器 实质: 一个缓存结构服务器或数据结 ...

  4. ssh登录失败的常见问题分析

    操作系统为了安全,一般只允许普通用户使用public_key登录,这时如果以root用户登录,就会出现各种错误.下面是常见的错误及解决方案. Permission denied (publickey) ...

  5. JdbcTemplate 的oracle分页

    @Autowired private JdbcTemplate jd; int ps1=Integer.valueOf(pageSize); int cp1=Integer.valueOf(currP ...

  6. 建立一个更高级别的查询 API:正确使用Django ORM 的方式

    https://www.oschina.net/translate/higher-level-query-api-django-orm

  7. JS检查断网

    window.addEventListener('load', function() { function updateOnlineStatus(event) { var condition = na ...

  8. export export-default import 使用场景

    export export-default import 使用场景:https://blog.csdn.net/weixin_36222137/article/details/77453774

  9. Codesforces 485D Maximum Value

                                                      D. Maximum Value   You are given a sequence a cons ...

  10. 用dialog包制作窗口

    #!/bin/bash temp=$(mktemp -t test.XXXXXX) temp2=$(mktemp -t test.XXXXXX) function diskspace { df -k ...