python操作haproxy配置文件实例
生活随笔
收集整理的這篇文章主要介紹了
python操作haproxy配置文件实例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
配置文件模板: defaultslog?globalmode?httpoption?httpcloseoption?dontlognulloption?abortoncloseoption?redispatchretries?3maxconn?20480balance?roundrobintimeout?connect?15000timeout?client?15000timeout?server?15000listen?admin_statbind?*:2008mode?httpoption?httplogstats?refresh?30sstats?uri?/statusstats?realm?Haproxy\?Statisticsstats?auth?admin:123456stats?hide-versionstats?admin?if?TRUElisten?image.eddy.com_LBbind?10.25.16.11:8000balance?roundrobinoption?forwardforoption?originaltomode?httpbalance?roundrobinserver??pwepaypubc0101??pwepaypubc0101:8000?check?inter?5000??weight?1server??pwepaypubc0102??pwepaypubc0102:8000?check?inter?5000??weight?1listen?payment.eddy.com:8080_HAbind?10.25.16.11:8080mode?tcpserver??pwepaypubc0101?pwepaypubc0101:8080?check?inter?5000??weight?1server??pwepaypubc0102?pwepaypubc0102:8080?check?inter?5000??weight?1?backup1.查詢配置文件 #!/usr/bin/env?python #?encoding:?utf-8 import?json import?re import?linecache import?time import?shutil #定義listen行號列表 listen_line?=?[] #定義文件行號列表 line?=?[] #定義文件內容列表 line_content?=?[] #定義listen行號與listen那一行內容字典 listen_dic?=?{} def?query_cfg(key):#打開文件with?open('haproxy.cfg','r')?as?obj:#循環文件行號與行內容for?(num,value)??in?enumerate(obj):#添加行號列表line.append(num)line_content.append(value)#匹配以listen開頭的行if?re.match('(listen.*?)',value,re.S):#添加listen的行號listen_line.append(num)#讓行內容之間的空格用‘_’替換value?=?str(value).replace('?','_')#添加listen行號和所在行號內容listen_dic.setdefault(num,value)#遍歷listen行號與內容的字典for?k,v?in?listen_dic.items():#匹配以listen開頭中間任意字符以關鍵字結尾的if?re.match('(listen.*?%s)'?%(key),v,re.S):#定義關鍵字所在listen行號key_line?=?listen_line.index(k)#判斷關鍵字listen行號是否是最后一個listen行號if?key_line+1?==?len(listen_line):#打印listen關鍵字行號到最后一行的內容for?i?in?range(listen_line[key_line],line[-1]+2):linecache.updatecache('haproxy.cfg')print?linecache.getline('haproxy.cfg',i),else:#判斷關鍵listen行號不是最后一個listen就打印兩個listen行號之間的內容for?i?in?range(listen_line[key_line],listen_line[key_line+1]):linecache.updatecache('haproxy.cfg')print??linecache.getline('haproxy.cfg',i), query_cfg('payment.eddy.com:8080_HA') Connected?to?pydev?debugger?(build?135.1057) listen?payment.eddy.com:8080_HAbind?10.25.16.11:8080mode?tcpserver??pwepaypubc0101?pwepaypubc0101:8080?check?inter?5000??weight?1server??pwepaypubc0102?pwepaypubc0102:8080?check?inter?5000??weight?1?backup? #2.為配置文件添加節點??????? def?add_cfg():read?=?raw_input("please?input?listen:")result?=?exist_cfg(read)if?result:print?'please?choose?another?listen?name'else:content?=?raw_input('please?input?listen?content:')#格式化輸入內容content_dict?=?json.loads(content)listen_title?=?'\n'?+?'listen'?+?'???'?+?content_dict['listen']record?=?content_dict['record']listen_bind?=?'\n'?+?'?????'?+?'bind'?+?'???'?+?record['bind']listen_mode?=?'\n'?+?'?????'?+?'mode'?+?'???'?+?record['mode']result1?=?exist_cfg(content_dict['listen'])if?result1:print?'please?choose?another?listen?name'else:#備份原配置文件shutil.copyfile('haproxy.cfg','haproxy_version_%s.cfg'?%time.strftime('%Y%m%d%H%M'))with?open('haproxy.cfg','a')?as?obj:obj.writelines(listen_title)obj.writelines(listen_bind)obj.writelines(listen_mode)obj.writelines('\n?????server?%s?check?inter?%s?weight?%s?maxconn?%s?\n'?%(record['server'],record['check?inter'],record['weight'],record['maxconn']))print?'add?successfull' add_cfg()? Connected?to?pydev?debugger?(build?135.1057) please?input?listen:abcd listen?is?not?exits please?input?listen?content:{"listen":"abcd","record":{"bind":"10.25.16.11:8002","mode":"http","server":"pwpaystoc0102?10.25.19.52:8002","check?inter":"5000","weight":"1","maxconn":"1000"}} listen?is?not?exits add?successfull 配置文件添加以下內容 listen???abcdbind???10.25.16.11:8002mode???httpserver?pwpaystoc0102?10.25.19.52:8002?check?inter?5000?weight?1?maxconn?1000? #3.為配置更新 def?update_cfg1():line_content?=?[]listen_list?=?[]line?=?[]with?open('haproxy.cfg','r')?as?obj:for?(num,value)??in?enumerate(obj):line_content.append(value)line.append(num)if?re.match('(listen.*?)',value,re.S):listen_list.append(num)#?content?=?'{"listen":"abcd","record":{"server":"pwpaystoc0102?10.25.19.52:8002","check?inter":"5000","weight":"1","maxconn":"1000"}}'content?=raw_input('please?update?site:')content_dict?=?json.loads(content)listen_title?=?content_dict['listen']record?=?content_dict['record']input_content?=?'???????server?%s?check?inter?%s?weight?%s?maxconn?%s?\n'?%(record['server'],record['check?inter'],record['weight'],record['maxconn'])for?i?in?line_content:if?re.match('(listen.*?%s)'?%(listen_title),i,re.S):if??line_content.index(i)?==?listen_list[-1]:line_content.insert(line[-1]+1,input_content)s?=?''.join(line_content)shutil.copyfile('haproxy.cfg','haproxy_version_%s.cfg'?%time.strftime('%Y%m%d%H%M'))with?open('haproxy.cfg','w')?as?obj:obj.write(s)else:current_listen_index?=?listen_list.index(line_content.index(i))next_listen_index?=?current_listen_index?+?1line_content.insert(listen_list[next_listen_index]-1,input_content)s?=?''.join(line_content)shutil.copyfile('haproxy.cfg','haproxy_version_%s.cfg'?%time.strftime('%Y%m%d%H%M'))with?open('haproxy.cfg','w')?as?obj:obj.write(s) update_cfg1()? Connected?to?pydev?debugger?(build?135.1057) please?update?site:{"listen":"abcd","record":{"server":"pwpaystoc0102?10.25.19.52:8002","check?inter":"5000","weight":"1","maxconn":"1000"}} 配置文件更新如下 listen???abcdbind???10.25.16.11:8002mode???httpserver?pwpaystoc0102?10.25.19.52:8002?check?inter?5000?weight?1?maxconn?1000?server?pwpaystoc0102?10.25.19.52:8002?check?inter?5000?weight?1?maxconn?1000?server?pwpaystoc0102?10.25.19.52:8002?check?inter?5000?weight?1?maxconn?1000 #4.刪除配置文件的配置 def?delete_cfg():read?=?raw_input("please?input?listen:")result??=?exist_cfg(read)if?result:for?k,v?in?listen_dic.items():if?re.match('(listen.*?%s)'?%(read),v,re.S):key_line?=??listen_line[listen_line.index(k)]if?key_line?==?listen_line[-1]:print?key_lineprint?line[-1]else:key_line1?=?listen_line[listen_line.index(k)+1]-2print?key_lineprint?key_line1read?=?raw_input("please?input?delete?line?number:")del?line_content[int(read)]shutil.copyfile('haproxy.cfg','haproxy_version_%s.cfg'?%time.strftime('%Y%m%d%H%M'))with?open('haproxy.cfg','w')?as?obj:new_realserver?=?''.join(line_content)obj.write(new_realserver)??? Connected?to?pydev?debugger?(build?135.1057) please?input?listen:abcdlisten???abcdbind???10.25.16.11:8002mode???httpserver?pwpaystoc0102?10.25.19.52:8002?check?inter?5000?weight?1?maxconn?1000?server?pwpaystoc0102?10.25.19.52:8002?check?inter?5000?weight?1?maxconn?1000? listen?is?exits 97 101 please?input?delete?line?number:101 配置文件如下: listen???abcdbind???10.25.16.11:8002mode???httpserver?pwpaystoc0102?10.25.19.52:8002?check?inter?5000?weight?1?maxconn?1000?注意: 1.以上輸入內容必須為以下格式{"listen":"fastdfs_group2_8002_external","record":{"bind":"10.25.16.11:8002","mode":"http","server":"pwpaystoc0102?10.25.19.52:8002","check?inter":"5000","weight":"1","maxconn":"1000"}}因為raw_input輸入的內容都為字符串,需要json化 2.注意寫入內容的空格與換行符 3.擴展1:你可以使用flask或django做成網頁管理haproxy配置文件的方式; 4.擴展2:你可以使用while?True的死循環方式把幾個函數連接起來做成一個終端操作的小工具,以下代碼是否可用,沒有驗證過,只是舉例 #?????while?True: #?????????print?''' #?????????????????=================================================== #?????????????????1.)select?haproxy?configuration #?????????????????2.)add?haproxy?listen #?????????????????3).update?haproxy #?????????????????4.)delete?haproxy?realserver #?????????????????=================================================== #?????????????????''' #?????????read?=?raw_input('please?choose?number:') #?????????if?read?==?'1': #?????????????site?=?raw_input('please?input?listen:') #?????????????exist_cfg(site) #?????????elif?read?==?'2': #?????????????add_cfg() #?????????elif?read?==?'3': #?????????????update_cfg() #?????????elif?read?==?'4': #?????????????delete_cfg() #?????????elif?read?==?'q'?or?read?==?'quit': #?????????????break轉載于:https://my.oschina.net/eddylinux/blog/537174
總結
以上是生活随笔為你收集整理的python操作haproxy配置文件实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JQ之路——layer第三方弹窗
- 下一篇: 4.集合