当前位置:小鱼儿玄机二站 > 编程应用 > python之haproxy配置文件操作

python之haproxy配置文件操作

文章作者:编程应用 上传时间:2019-09-03

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条目款项,步入修改环节
     4、输入4,步向backend菜单,采纳server条约,步入删除环节
     5、输入5,退出程序

三、haproxy配置文件如下:

图片 1global 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 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.10 100.1.7.10 weight 10 maxconn 2000 frontend mysql bind *:3306 mode tcp log global default_backend mysqlserver backend mysqlserver server mysql1 10.1.1.110:3306 weight 20 maxconn 300 server mysql2 10.1.1.120:3306 weight 10 maxconn 200 haproxy配置文件

 

四、流程图如下:

 #!/usr/bin/python27 #_*_ coding=utf-8 _*_ ''' Created on 2016年1月17日 @author: 王凯 ''' import os,sys,re,time from collections import defaultdict,OrderedDict ######################raw_input输入字符类型转化函数####################### def input_handle(s): if str.isdigit(s): ###对输入是或不是是数字举行剖断### s = int(s) ###一旦出口的是个数字,则转向为整数档期的顺序### return s ###回去输入字符### #####################名称或变量名输入判别函数############################# def name_decide(): (name,name_flag) = ('',True) ###初阶化重临的称谓和剖断标记位### while name_flag: name_input = raw_input('33[32m请输入新劳动名:(退出输入q)33[0m') if len(name_input) == 0: ###假若输入为空则直接下二回巡回### continue elif name_input == 'q': ###输入q,退出这一次输入### name_flag = False elif re.match('[0-9a-zA-Z_]+',name_input): ###相配输入是不是以字符、数字或下划线初叶### name = name_input name_flag = False ###输入成功后脱离循环### else: print('33[31m称号输入错误,请重新输入!!!33[0m') return(name) ###重临输入的结果### #####################IP地址及端口输入推断函数############################# def ipaddress_decide(): (address,address_flag) = ('',True) ###开头化再次回到的IP地址和判别标记位### while address_flag: address_input = raw_input('33[32m请输入新鸿基土地资金财产点(IP哦):(退出输入q)33[0m') if len(address_input) == 0: ###一经输入为空则直接下一遍巡回### continue elif address_input == 'q': ###输入q,退出这一次输入### address_flag = False ##################合作输入是还是不是是ip:port的格式###################### elif re.match('(25[0-5]|2[0-4]d|[0-1]?d?d)(.(25[0-5]|2[0-4]d|[0-1]?d?d)){3}(:d{1,5})?$',address_input): address = address_input address_flag = False ###输入成功后脱离循环### else: print('33[31m地方输入错误,请重新输入!!!33[0m') return(address) ###归来输入的结果### ####################数字输入判定函数###################################### def number_decide(name): (number,number_flag) = ('',True) ###早先化重临的数字和判定标记位### while number_flag: number_input = raw_input('33[32m请输入 %s (数字哦):(退出输入q)33[0m' % name) if len(number_input) == 0: ###假设输入为空则间接下叁回巡回### continue elif number_input == 'q': ###输入q,退出本次输入### number_flag = False else: try: int(number_input) ###合作输入是还是不是是数字### except: print('33[31m %s 输入错误,请重新输入!!!33[0m' % name) else: number = number_input number_flag = False ###输入成功后退出循环### return(number) ###回来输入的结果### #############################backend输入决断函数########################## def backend_input_if(input_index,input_dict): (input_name,input_flag) = ('',True) ###早先化再次回到的称号和决断标记位### ###############假如输入非空,对输入进行推断并转化项目################# if len(input_index) != 0: input_index = input_handle(input_index) if input_index == 'b': ###就算输入为b,则脱离程序### input_flag = False elif input_index in input_dict.keys(): ###假如输入为数字编号,则从字典中获取具体backend名称### input_name = input_dict[input_index] elif input_index in input_dict.values(): ###举个例子输入为backend名称,则间接拿走### input_name = input_index else: input_name = '' ###输入任何字符,赋值变量为空### return(input_name,input_flag) ###回到输入的结果和循环标识位### ###########################backend列表浮现函数############################ def backend_read(file): backend_list = [] ###初始化backend的列表### show_dict = {} ###早先化要赶回的浮现字典### backend_name_dict = defaultdict(list) ###概念三个value为列表的字典,用来存放在server### server_flag = False ###初步化server剖断标识位### with open(file,'r') as ha: ###展开haproxy配置文件### for line in ha: server_dict = OrderedDict() ###概念叁个逐步字典### line = line.strip('n') if re.match('backend',line): ###相配配置文件以backend开始的行### backend_name = re.split('s+',line)[1] backend_list.append(backend_name) ###将配置到的backend的称号插入到列表### server_flag = True ###赋值标识位为真,用来与server关联### elif server_flag and re.match('s+server',line): ###非常配置文件以server起首的行### server_info = re.split('s+',line) ###对server进行分隔### server_dict['name'] = server_info[2] ###对server的现实性音讯实行字典赋值### server_dict['address'] = server_info[3] server_dict['weight'] = server_info[5] server_dict['maxconn'] = server_info[7] backend_name_dict[backend_name].append(server_dict) ###将server字典与backend的称号实行关联### else: server_flag = False ###当server没相称到,赋值标记位为假,截至关系### for k,v in enumerate(backend_list,1): show_dict[k] = v ###对backend名称进行新字典赋值,方便查询和展现### print('%d . %s' % (k,v)) ###输出backend列表### return(show_dict,backend_name_dict) ###回去呈现的字典和backend-server字典### ########################呈现backend后端服务器函数############################# def backend_server_show(backend_show_value,server_show_dict): ############对backend名称举行遍历并加上数字编号########################### print('n================================================================') print('后端服务器(%s)音信如下 : ' % backend_show_value) print('%-5s %-20s %-20s %-20s %-20s' % ('id','name','address','weight','maxconn')) server_list = server_show_dict[backend_show_value] for k,v in enumerate(server_list,1): ###用enumerate进行server展示### print '%-5s' % k + ' ', for kk,vv in v.items(): print '%-20s' % vv + ' ', print print('n================================================================') ########################backend后端服务操作并回写配置文件函数################# def backend_server_handle(file,handle_dict): newfile = '%s.new' % file ###概念回写的新文件### server_flag = False with open(file,'r') as read_file,open(newfile,'w') as write_file: ###还要张开二文本,叁个读,多少个写### for line in read_file: if re.match('backend',line): ###卓越到backend行时打开server消息插入### write_file.write(line) backend_name = re.split('s+',line)[1] for server_dict in handle_dict[backend_name]: ###对backend-server字典举行遍历### server_line = 'tserver {name} {address} weight {weight} maxconn {maxconn}n' write_file.write(server_line.format(**server_dict)) ###将点名的backend下的server条目款项插入文件### server_flag = True ###点名标识位为真,方便server剖断### elif server_flag and re.match('s+server',line): ###匹配server开首的行,跳过不做别的操作### pass else: write_file.write(line) ###其余的行,直接插入新文件### server_flag = False print('33[33m server更新成功33[0m') os.system('mv %s %s.bak' % (file,file)) ###对源配置文件实行备份### os.system('mv %s %s' % (newfile,file)) ###对新生成的安顿文件进行更名### ##################################主程序起头################################## if __name__ == '__main__': flag = True haproxy_file = 'haproxy.cfg' ###点名haproxy配置文件### backend_name = '' haproxy_name_show_dict = {} ###起首化backend展现字典### haproxy_server_show_dict = {} ###开首化server显示字典### while flag: os.system('clear') ###清屏### print('n================================================================') print('33[33m 应接访谈haproxy配置文件处理平台:33[0m') print('nbackend列表新闻如下 : ') (haproxy_name_show_dict,haproxy_server_show_dict) = backend_read(haproxy_file) print('n================================================================') print ''' 33[31m 1. 询问后端服务33[0m 33[32m 2. 抬高后端服务33[0m 33[33m 3. 退换后端服务33[0m 33[35m 4. 去除后端服务33[0m 33[36m 5. 退出33[0m ''' print('n================================================================') select_num = raw_input('33[33m请选用操作条款:33[0m') #######################1. 询问后端服务################################ if select_num == '1': query_flag = True ###初阶化查询循环标记### while query_flag: backend_index = raw_input('33[32;1m请输入查询的backend编号或名称(重返上层菜单,请输入b):33[0m') ##############################对输入值进行判别################ (backend_name,query_flag) = backend_input_if(backend_index,haproxy_name_show_dict) if backend_name: ###呈现对应backend下的server列表### backend_server_show(backend_name,haproxy_server_show_dict) #######################2. 加上后端服务################################ if select_num == '2': add_flag = True ###开头化增加循环标记### while add_flag: backend_index = raw_input('33[32;1m请输入增添的backend的号子或称谓(重返上层菜单,请输入b):33[0m') ##############################对输入值实行剖断################ (backend_name,add_flag) = backend_input_if(backend_index,haproxy_name_show_dict) if backend_name: ###展现对应backend下的server列表### backend_server_show(backend_name,haproxy_server_show_dict) add_server_dict = OrderedDict() print('33[34;1m请依次输入后端服务消息(name,address,weight,maxconn):33[0m') add_server_dict['name'] = name_decide() ###对输入的name有效性举办判别### add_server_dict['address'] = ipaddress_decide() ###对输入的IP有效性进行剖断### add_server_dict['weight'] = number_decide('权重值') ###对输入的权重有效性进行判别### add_server_dict['maxconn'] = number_decide('最亚松森接数') ###对输入的连接数有效性进行决断### print(add_server_dict['name'],add_server_dict['address'],add_server_dict['weight'],add_server_dict['maxconn']) #############对输入的三个劳务消息是不是中标判定############# if add_server_dict['name'] and add_server_dict['address'] and add_server_dict['weight'] and add_server_dict['maxconn']: add_commit = raw_input('请确认是或不是增加此条目款项(y | n):') if add_commit == 'y': ###认同增添服务条目款项,并回写配置文件### haproxy_server_show_dict[backend_name].append(add_server_dict) backend_server_handle(haproxy_file,haproxy_server_show_dict) else: add_flag = False ###要不然退出这一次巡回### else: print('33[31m server输入消息有误,请重新输入!!!33[0m') #######################3. 改造后端服务################################# if select_num == '3': backend_modify_flag = True ###最初化修改循环标记### while backend_modify_flag: backend_index = raw_input('33[32;1m请输入修改的backend的数码或称谓(重返上层菜单,请输入b):33[0m') ##############################对输入值进行判别################ (backend_name,backend_modify_flag) = backend_input_if(backend_index,haproxy_name_show_dict) if backend_name: ###展示对应backend下的server列表### backend_server_show(backend_name,haproxy_server_show_dict) server_modify_flag = True ###开端化server条约修改标识位### while server_modify_flag: server_index = raw_input('33[32;1m请输入修改的server的号子(重返上层菜单,请输入b):33[0m') if len(server_index) != 0: server_index = input_handle(server_index) if server_index == 'b': ###输入b,返还上一层### server_modify_flag = False #####################内定具体的server编号举行推断##### elif server_index >= 1 and server_index <= len(haproxy_server_show_dict[backend_name]): modify_server_dict = OrderedDict() print('33[34;1m请依次输入后端服务消息(name,address,weight,maxconn):33[0m') modify_server_dict['name'] = name_decide() ###对输入的多个新闻有效实行判断### modify_server_dict['address'] = ipaddress_decide() modify_server_dict['weight'] = number_decide('权重值') modify_server_dict['maxconn'] = number_decide('最辛辛那提接数') print(modify_server_dict['name'],modify_server_dict['address'],modify_server_dict['weight'],modify_server_dict['maxconn']) ######对输入的多少个服务新闻是或不是中标推断############# if modify_server_dict['name'] and modify_server_dict['address'] and modify_server_dict['weight'] and modify_server_dict['maxconn']: modify_commit = raw_input('请确认是否修改此条目款项(y | n):') if modify_commit == 'y': ###确认修改服务条目款项,并回写配置文件### haproxy_server_show_dict[backend_name][server_index - 1] = modify_server_dict backend_server_handle(haproxy_file,haproxy_server_show_dict) modify_server_flag = False else: ###要不退出此番巡回### modify_server_flag = False else: print('33[31m server输入新闻有误,请重新输入!!!33[0m') else: print('33[31m server编号输入错误,请重新输入!!!33[0m') #######################4. 刨除后端服务################################ if select_num == '4': backend_delete_flag = True ###伊始化删除循环标识### while backend_delete_flag: backend_index = raw_input('33[32;1m请输入删除的backend下条目款项编号或称谓(重临上层菜单,请输入b):33[0m') ##############################对输入值进行决断################ (backend_name,backend_delete_flag) = backend_input_if(backend_index,haproxy_name_show_dict) if backend_name: ###呈现对应backend下的server列表### backend_server_show(backend_name,haproxy_server_show_dict) server_delete_flag = True ###最初化server条目款项删除标记位### while server_delete_flag: server_index = raw_input('33[32;1m请输入删除的server的号子(重临上层菜单,请输入b):33[0m') if len(server_index) != 0: server_index = input_handle(server_index) if server_index == 'b': ###输入b,返还上一层### server_delete_flag = False #####################钦赐具体的server编号实行判别##### elif server_index >= 1 and server_index <= len(haproxy_server_show_dict[backend_name]): print(haproxy_server_show_dict[backend_name][server_index - 1]) delete_commit = raw_input('请确认是否删除此条款(y | n):') if delete_commit == 'y': ###认可删除服务条款,并回写配置文件### del haproxy_server_show_dict[backend_name][server_index - 1] backend_server_handle(haproxy_file,haproxy_server_show_dict) delete_server_flag = False else: ###不然退出此番巡回### delete_server_flag = False else: print('33[31m server编号输入错误,请重新输入!!!33[0m') #######################5. 脱离程序###################### if select_num == '5': sys.exit('33[32m 退出程序,接待下一次光临,多谢33[0m') haproxy_python27

 

六、python3.4代码:

图片 2import time,os,datetime,sys,MySQLdb,logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%Y %m %d %H:%M:%S', # filename=filename, filename='/home/logs/svncommit.log', filemode='a') g_DB_CONFIG={ 'host':'127.0.0.1', 'user':'root', 'passwd':'', 'db':'' } def GetCurPathInfo(): today_time=datetime.datetime.now() today_0_time = datetime.datetime(today_time.year, today_time.month, today_time.day) yestoday_time=datetime.datetime.now()-datetime.timedelta(days=0) yestoday_0_time = datetime.datetime(yestoday_time.year, yestoday_time.month, yestoday_time.day) todayUnix = int(time.mktime(today_0_time.timetuple())) yesterdayUnix = int(time.mktime(yestoday_0_time.timetuple())) logging.info('yestertoday : date %s, unix_time %s' %(yestoday_0_time,yesterdayUnix)) logging.info('today : date %s, unix_time %s' %(today_0_time,todayUnix)) CurPath='/home/svnroot' ChildrenList = os.listdir(CurPath) # logging.info(ChildrenList) appidList=[] index = 0 for name in ChildrenList: index = index + 1 if index%500==0: logging.info (index) if len(name) != 14: continue dbName = os.path.join(CurPath,name,'db') if not os.path.exists(dbName): logging.info('db is not exists, appId is '+name) continue # logging.info(dbName) appFileStats = os.stat(os.path.join(CurPath,name)) appModifyTime = appFileStats.st_mtime fileStats = os.stat(dbName) modifyTime = fileStats.st_mtime if modifyTime > yesterdayUnix : appidList.append(name) logging.info ('today create appid submit '+name) logging.info (appidList) logging.info ('len is :' +str(len(appidList))) yestoday_timeStr='%d-%02d-%02d' % (yestoday_time.year, yestoday_time.month,yestoday_time.day) # logging.info(yestoday_timeStr) values=[] svn_ip='10.124.156.225' for appid in appidList: values.append((appid,yestoday_timeStr,svn_ip)) # logging.info(values) # try: # conn=MySQLdb.connect(host=g_DB_CONFIG['host'],user=g_DB_CONFIG['user'],passwd=g_DB_CONFIG['passwd'],port=3306,db=g_DB_CONFIG['db']) # cur=conn.cursor() # cur.executemany('insert ignore into statistic_svncommit(appId,reportDate,svn_ip) values(%s,%s,%s)',values) # conn.commit() # cur.close() # conn.close() # except MySQLdb.Error,e: # logging.info( "Mysql Error %d: %s" % (e.args[0], e.args[1])) # raise e return if __name__ == '__main__': try: logging.info('-'*60 +'begin Statistic_Svncommit'+'-'*60) GetCurPathInfo() logging.info('-'*60+'end Statistic_Svncommit'+'-'*60) except: info = sys.exc_info() for file, lineno, function, text in traceback.extract_tb(info[2]): logging.error(text) else: logging.info('SUCCESS') haproxy_python34

 

 七、效果图:

1、  初始菜单直接显示backend列表,并列出选取菜单:

 注:

name以数字、字母、下划线开端(当中积攒数字的来头是能够输入ip地址)

address能够是独自的ip地址,也能够是ip加端口的款型,例:192.168.100.3或192.168.100.3:8080

weight和maxconn必需输入数字,大小暂前卫未限定

 

5、 输入b能够重临上层菜单,输入3步入修改server条约,并对www.oldboy.org下的sky条目款项举办退换:

 图片 3

          一样对输入的server有效性举行决断,最后确认回写配置文件,查看修改结果:

 图片 4

 

6、  输入b可以回来上层菜单,输入4进去删除server条约,并对点名条约进行改变:

 图片 5

7、输入b能够回去上层菜单,输入5,就能够退出程序。

 

八、针对python2.7和python3.4的代码不同:

       1、print的使用。

       2、python2.7下使用raw_input,python3.4下使用input。

作业: 对haproxy配置文件进行操作 须求: 对haproxy配置文件中backend下的server完毕增加和删除改查的成效 一...

s13 day3作业,s13day3

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文件音讯

图片 6 1 global 2 log 127.0.0.1 local2 3 daemon 4 maxconn 256 5 log 127.0.0.1 local2 info 6 defaults 7 log global 8 mode http 9 timeout connect 5000ms 10 timeout client 50000ms 11 timeout server 50000ms 12 option dontlognull 13 14 listen stats :8888 15 stats enable 16 stats uri /admin 17 stats auth admin:1234 18 19 frontend oldboy.org 20 bind 0.0.0.0:80 21 option httplog 22 option httpclose 23 option forwardfor 24 log global 25 acl www hdr_reg(host) -i www.oldboy.org 26 use_backend www.oldboy.org if www 27 28 backend www.oldboy.org 29 server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000 30 server 100.1.7.9 100.1.7.9 weight 20 maxconn 300 31 server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000 ha_file

下面是首要程序代码,

图片 7 1 #!/use/bin/env python 2 #_*_ coding:utf_8 _*_ 3 import json,time,os,sys 4 5 time_now=time.strftime('%Y-%m-%d %H:%M:%S') 6 time_flag=time.strftime('%Y-%m-%d-%H-%M-%S') 7 8 9 if __name__ =='__main__': 10 """ 11 主函数,通过判别顾客输入实施相应操作 12 :return: 13 """ 14 while True: 15 print( 16 ''' 17 --------------------------------------- 18 请输入下列编号实行操作,按q退出: 19 1:获取haproxy记录 20 2:扩展haproxy记录 21 3: 删除haproxy记录 22 ---------------------------------------- 23 ''') 24 get_mun = input('请输入操作序号:') 25 if get_mun == 'q': 26 exit('bye') 27 if get_mun.isdigit: 28 get_mun = int(get_mun) 29 if get_mun == 1: #若果选用1,则实行get_ha() 30 read = input("请输入backend:(例如:www.oldboy.org)") 31 ha_list = get_ha(read) 32 if len(ha_list)!= 0: 33 print(ha_list) 34 else: 35 print('未有找到呼应记录,请检查输入是或不是科学') 36 elif get_mun == 2: 37 add_ha() 38 elif get_mun == 3: 39 del_domain = input('请输入想要删除的值:') 40 del_ha(del_domain) main()

main函数调用别的多少个函数,分别为查询记录,扩充记录和删除记录

概念查询函数

图片 8 1 def get_ha(get_read): 2 """ 3 定义查询函数 4 :param get_read:客户输入想查询的音信 5 :return:重返查询结果 6 """ 7 get_flags = 0 #设置标记符,当相配到输入时置为1 8 get_list = [] #将非常到的内容放在列表中 9 with open('ha_file','r',encoding='utf-8') as f: 10 for line in f.readlines(): 11 line = line.strip() #去掉多余的空格和换行符 12 if line == 'backend %s'%get_read: 13 get_flags = 1 14 elif line.startswith('backend'): 15 get_flags = 0 16 elif get_flags == 1 and len(line)!= 0 : 17 get_list.append(line) 18 return get_list get_ha()

概念增添函数

图片 9 1 def add_ha(): 2 while True: 3 add_resource_str = input('请输入想要扩展的笔录: ') 4 result_check = check_input(add_resource_str) 5 if result_check == False: 6 print('请输入准确格式') 7 if result_check == True: 8 add_resource = json.loads(add_resource_str) #获取输入的值 9 domain_info = add_resource['backend'] 10 server_info = add_resource['record']['server'] 11 weight_info = add_resource['record']['weight'] 12 maxcont_info = add_resource['record']['maxconn'] 13 match_info = ('server {} {} weight {} maxconn {}').format(server_info,server_info,weight_info,maxcont_info) 14 #match_info 剖断新闻是不是留存,不设有则加多进文件 15 # print(match_info,type(match_info)) 16 # print(domain_info) 17 get_match = get_ha(domain_info) #最初的文章件已经存在的记录 18 # print(get_match[0]) 19 if get_match != []:#域名消息存在 20 if get_match[0] == match_info: 21 print('音信已存在,不做改造') 22 else: 23 #域名新闻留存,然而有更新,f1为原版的书文件,f2为备份文件 24 with open('ha_file','r',encoding='utf-8') as f1: 25 all_config = f1.readlines() 26 match_item = 'backend {}n'.format(domain_info) #收获立异后的安顿新闻 27 #print(match_item) 28 if str(match_item) in all_config: 29 update_index = all_config.index(str(match_item)) 30 insert_record_index = int(update_index) +1 31 all_config.insert(int(insert_record_index),8*' '+match_info+'n') #将数据插入 32 with open('ha_new','w',encoding='utf-8') as f2: 33 f2.writelines(all_config) 34 os.rename('ha_file','ha_bak%s'%(time_flag)) 35 os.rename('ha_new','ha_file') 36 else: #原来的书文件一纸空文一样域名,追加到文件末尾 37 with open('ha_file','r',encoding='utf-8') as f1,open('ha_new','w',encoding='utf-8') as f2: 38 all_config = f1.readlines() 39 str_append = (''' 40 backend %s 41 %s 42 '''%(domain_info,match_info))# 字符串预格式化 43 all_config.append(str_append) 44 f2.writelines(all_config) 45 os.rename('ha_file','ha_bak') 46 os.rename('ha_new','ha_file') 47 return add_ha

概念删除函数

图片 10 1 def get_ha(get_read): 2 """ 3 定义查询函数 4 :param get_read:顾客输入想询问的新闻 5 :return:再次回到查询结果 6 """ 7 get_flags = 0 #安装标志符,当相称到输入时置为1 8 get_list = [] #将同盟到的剧情放在列表中 9 with open('ha_file','r',encoding='utf-8') as f: 10 for line in f.readlines(): 11 line = line.strip() #去掉多余的空格和换行符 12 if line == 'backend %s'%get_read: 13 get_flags = 1 14 elif line.startswith('backend'): 15 get_flags = 0 16 elif get_flags == 1 and len(line)!= 0 : 17 get_list.append(line) 18 return get_list del_ha

出于此番为手动输入记录,对格式有严刻的须要,所以定义三个检查输入的函数。实际条件中应当是从其余地方get到格式化好的值。

图片 11 1 def check_input(check_dir): 2 """ 3 检查输入格式是不是精确 4 :param check_str: 5 :return: 6 """ 7 try: 8 check = json.loads(check_dir) 9 domain_info = check['backend'] 10 server_info = check['record']['server'] 11 weight_info = check['record']['weight'] 12 maxcont_info = check['record']['maxconn'] 13 14 except: 15 return False 16 else: 17 return True check_input

 

day3作业,s13day3 ha_proxy配置文件修改程序 ha_file 为存款和储蓄配置音信的公文。运转的时候对该文件实行操作。 1.询问消息:客户输入域名,获...

本文由小鱼儿玄机二站发布于编程应用,转载请注明出处:python之haproxy配置文件操作

关键词: