Python小程序之动态修改Haproxy配置文件

需求如下:

  1、动态的查询添加删除haproxy节点信息

  2、程序功能:add(添加)、Del(删除)、Query(查询)

  3、添加时实例字符串为:  {'backend': 'www.oldboy.com','record': {'server': '100.1.7.9','weight': 20,'maxconn': 30}}

代码:

  1 # Author:Lee Sir
  2 import sys
  3 
  4 
  5 haproxyconf = r"E:Python练习脚本day3haproxy.txt"
  6 haproxyconf_temp = r"E:Python练习脚本day3haproxy_temp.txt"
  7 
  8 def openconf(file,mode):
  9     fd = open(file,'%s' % mode)
 10     return fd
 11 
 12 def closeconf(fd):
 13     fd.close()
 14 
 15 def user_choice():
 16     choice = ['Query','Add','Delete','Update']
 17     for index,key in enumerate(choice):
 18         print(index,key)
 19     while True:
 20         userchoice = input('Please number for your Choice: ')
 21         if userchoice.isdigit() and int(userchoice) >= 0 and int(userchoice) < 3:
 22             return userchoice
 23         elif userchoice == 'q' or userchoice == 'Q':
 24             sys.exit('Bye Bye')
 25         else:
 26             print('Input Error,Please try again')
 27 
 28 def listnode():
 29     conf = openconf(haproxyconf,'r')
 30     key = input('Please Input Your Query Node Name: ')
 31     count = 0
 32     for line in conf:
 33         if key in line and line.strip().startswith('backend'):
 34             result = True
 35             nodenumber = 1
 36             while result:
 37                 nodeinfo = conf.readline()
 38                 if nodeinfo.strip().startswith('server'):
 39                     print('节点 %s:%s ' % (nodenumber,nodeinfo.strip()))
 40                     count += 1
 41                     nodenumber += 1
 42                 else:
 43                     result = False
 44     if count == 0:
 45         print('33[31;1mNo Node for %s33[0m' % key)
 46     closeconf(conf)
 47 
 48 def delenode():
 49     conf = openconf(haproxyconf,'r')
 50     key = input('Please input Delete Node: ')
 51     conf_list = []
 52     for line in conf:
 53         if line.strip().startswith('backend'):
 54             if key in line:
 55                 conf_list.append(line)
 56                 while True:
 57                     nodeinfo = conf.readline()
 58                     if nodeinfo.strip().startswith('server'):
 59                         conf_list.append(nodeinfo)
 60                     else:
 61                         break
 62     else:
 63         if len(conf_list) > 0:
 64             old_conf = openconf(haproxyconf,'r')
 65             write_conf = openconf(haproxyconf_temp,'w')
 66             for info in old_conf:
 67                 if info in conf_list:
 68                     continue
 69                 else:
 70                     write_conf.write(info)
 71             else:
 72                 closeconf(old_conf)
 73                 closeconf(write_conf)
 74                 print('Delete Node:%s Successful!'  % key )
 75         else:
 76             sys.exit('No Node info for %s' % key)
 77 
 78 def addnode():
 79     conf = openconf(haproxyconf_temp,'r')
 80 #    nodeinfo = '''{'backend': 'www.oldboy.com','record': {'server': '100.1.7.9','weight': 20,'maxconn': 30}}'''
 81     nodeinfo = input('Please input Your Add node info:')
 82     nodeinfo = eval(nodeinfo)
 83     if isinstance(nodeinfo,dict):
 84         backend = nodeinfo['backend']
 85         for line in conf:
 86             if line.strip().startswith('backend'):
 87                 if backend in line:
 88                     sys.exit('The node are exist!')
 89         else:
 90             add_wirte = openconf(haproxyconf_temp,'a')
 91             backend = nodeinfo['backend']
 92             record = nodeinfo['record']
 93             server = record['server']
 94             weight = record['weight']
 95             maxconn = record['maxconn']
 96             node_info = '''
backend %s
		server %s %s weight %s maxconn %s
 97             ''' %  (backend,server,server,weight,maxconn)
 98             add_wirte.write(node_info)
 99             print('The Node:%s Add Successful!' % backend )
100     else:
101         sys.exit('Input Error,bye bye!')
102 
103 
104 def main():
105     userchoice = user_choice()
106     if userchoice == '0':
107         listnode()
108     elif userchoice == '1':
109         addnode()
110     elif userchoice == '2':
111         delenode()
112 
113 
114 if __name__ == '__main__':
115     main()
原文地址:https://www.cnblogs.com/dachenzi/p/6568979.html