PYTHON Modify configuration file

Source: Internet
Author: User
Tags haproxy

Knowledge to be mastered:

1. Functions

2. File processing

3, the use of tag

4, the decoupling of the program

Demand:

1: Query
2: Add
3: Delete
4: Modify
5: Exit

Haproxy.conf Configuration file Contents:

 1 Global 2 log 127.0.0.1 local2 3 daemon 4 maxconn 5 log 127.0.0.1 local2 info 6 DEFA         Ults 7 Log Global 8 mode HTTP 9 Timeout connect 5000ms10 Timeout client 50000ms11       Timeout server 50000ms12 option Dontlognull13 Listen stats:888815 stats enable16 stats URI /admin17 Stats auth admin:123418 frontend oldboy.org20 bind 0.0.0.0:8021 option Httplo G22 option httpclose23 option forwardfor24 log global25 ACL www hdr_reg (host)-I www.oldb Oy.org26 use_backend www.oldboy.org If www27 backend www.oldboy1.org29 server 10.10.0.10 10.10.0.10 Wei ght 9999 maxconn 3333333333330 server 10.10.10.1 10.10.10.1 weight the maxconn 200031 server 2.2.2.4 2.2.2. 4 weight maxconn 300032 backend www.oldboy2.org33 server 3.3.3.3 3.3.3.3 weight-maxconn 300034 backend WWW.O Ldboy20.org35 SERVer 10.10.0.10 10.10.0.10 weight 9999 maxconn 33333333333 

 1 Global 2 log 127.0.0.1 local2 3 daemon 4 maxconn 5 log 127.0.0.1 local2 info 6 DEFA         Ults 7 Log Global 8 mode HTTP 9 Timeout connect 5000ms10 Timeout client 50000ms11       Timeout server 50000ms12 option Dontlognull13 Listen stats:888815 stats enable16 stats URI /admin17 Stats auth admin:123418 frontend oldboy.org20 bind 0.0.0.0:8021 option Httplo G22 option httpclose23 option forwardfor24 log global25 ACL www hdr_reg (host)-I www.oldb Oy.org26 use_backend www.oldboy.org If www27 backend www.oldboy1.org29 server 10.10.0.10 10.10.0.10 Wei ght 9999 maxconn 3333333333330 server 10.10.10.1 10.10.10.1 weight the maxconn 200031 server 2.2.2.4 2.2.2. 4 weight maxconn 300032 backend www.oldboy2.org33 server 3.3.3.3 3.3.3.3 weight-maxconn 300034 backend WWW.O Ldboy20.org35 SERVer 10.10.0.10 10.10.0.10 weight 9999 maxconn 33333333333 

First, the optimized code:

  1 #!/usr/bin/env Python 2 #-*-coding:utf-8-*-3 #Author: Nulige 4 5 6 import OS 7 def file_handle (filen Ame,backend_data,record_list=none,type= ' fetch '): #type: Fetch append change 8 new_file=filename+ ' _new ' 9 bak_file             =filename+ ' _bak ' if type = = ' fetch ': one r_list = [] with open (filename, ' R ') as F:13  Tag = False f:15 if line.strip () = = backend_data:16 Tag = True Continue if tag and line.startswith (' backend '): + b Reak if tag and line:21 r_list.append (Line.strip ()) in r_l ist:23 print (line) return r_list elif type = = ' Append ': + with open (Filena                 Me, ' R ') as Read_file, open (New_file, ' W ') as write_file:28 for R_line in read_file:29 Write_filE.write (R_line)-New_line in record_list:32 if New_line.startswith (' backend '): 33 Write_file.write (new_line + ' \ n ') else:35 write_file.write ("%s% s\n "% (' * 8, New_line)" os.rename (filename, bak_file) Notoginseng os.rename (new_file, filename) S.remove (bak_file) elif type = = ' Change ': + with open (filename, ' R ') as Read_file, ope N (new_file, ' W ') as write_file:42 tag=false Has_write=false-R_line in Read_ file:45 if r_line.strip () = = backend_data:46 Tag=true continu e if tag and r_line.startswith (' backend '): Tag=false if not t                         ag:51 write_file.write (r_line) else:53 if not has_write:54 For new_line in record_list:55 if New_line.startswith (' backend '): 56 Write_file.write (new_line+ ' \ n ') else:58 write_file. Write ('%s%s\n '% (' ' *8,new_line ') has_write=true os.rename (filename, bak_file) os.rename (new     _file, filename) os.remove (bak_file) + def fetch (data): Backend_data= "backend%s"%data 67 Return File_handle (' haproxy.conf ', backend_data,type= ' fetch ')------(data): backend=data[' backend ']                                                          Ecord_list=fetch (Backend) current_record= "server%s%s weight%s maxconn%s"% (data[' record '] [' Server '], 73                                                          data[' record ' [' Server '], 74 data[' record ' [' Weight '], data[' record ' [' Maxcon N '])Backend_data= "Backend%s"%backend if not record_list:79 record_list.append (backend_data) 80     Record_list.append (Current_record) Bayi file_handle (' haproxy.conf ', backend_data,record_list,type= ' append ') 82 else:83 Record_list.insert (0,backend_data) if Current_record not in Record_list:85 re Cord_list.append (Current_record) file_handle (' haproxy.conf ', backend_data,record_list,type= ' change ') Remove (data): backend=data[' backend ' Record_list=fetch (backend) current_record= "server%s%s weight %s Maxconn%s "% (data[' record '] [' Server '], data[' record ' [' ser]                                                          Ver '], data[' record ' [' Weight '], 94 data[' record ' [' Maxconn ']) Backend_data = "Backend%s"% backend if not Recor D_list or Current_record Not in record_list:97 print (' \033[33;1m no This record \033[0m ') 98 return else:100 if Len (record_li ST) = = 1: #判断record_list是否还有一条记录101 record_list.remove (Current_record) #如果只剩一条记录, put the last record and B Ackend removed 102 else:103 record_list.insert (0,backend_data) 104 Record_list.remove (current_re Cord) file_handle (' haproxy.conf ', backend_data,record_list,type= ' change ') 106 107 #{' backend ': ' www.oldboy20.org ' , ' record ': {' server ': ' 10.10.0.10 ', ' weight ': 9999, ' Maxconn ': 33333333333}}108 109 def Change (data): Backend=data[0] [' Backend ']111 record_list=fetch (backend) 113 old_record= "server%s%s weight%s maxconn%s"% (data[0][' record ')                                                          [' Server '],114 data[0][' record '] [' Server '],115                                                          data[0][' record ' [' Weight '],116 data[0][' record ' [' Max 'Conn ']) 117 118 New_record = "Server%s%s weight%s maxconn%s"% (data[1][' record '] [' Server '], 119                                                         data[1][' record ' [' Server '], 120 data[1][' record ' [' weight '], 121 data[1][' record ' [' Maxconn '] ) 122 Backend_data= "backend%s"%backend123 124 if not record_list or Old_record not in record_list:125 pri NT (' \033[33;1m without this content \033[0m ') 126 return127 else:128 Record_list.insert (0,backend_data) 129 index= Record_list.index (Old_record) record_list[index]=new_record131 file_handle (' haproxy.conf ', Backend_data,     Record_list,type= ' Change ') 133 134 if __name__ = = ' __main__ ': 135 msg= ' 136 1: Query 137 2: Add 138 3: Delete 139         4: Change 140 5: Exit 141 ' 142 menu_dic={143 ' 1 ': fetch,144 ' 2 ': add,145 ' 3 ': remove,146         ' 4 ': change,147' 5 ': exit,148}149 while true:150 print (msg) 151 choice=input ("Operation >>:"). Strip () if Len (choice) = = 0 or choice not in menu_dic:continue153 if choice = = ' 5 ': break154 155 data=input ("Data >&gt ;: "). Strip () 156 157 #menu_dic [Choice] (data) ==fetch (data) 158 if choice! = ' 1 ': 159 Data=eval (DA TA) Menu_dic[choice] (data) #add (data) 161 162 163 # [{' backend ': ' www.oldboy20.org ', ' record ': {' server ': ' 2.2.2.3 ', ' Weight ': ' maxconn ': 3000}},{' backend ': ' www.oldboy10.org ', ' record ': {' server ': ' 10.10.0.10 ', ' weight ': 9999, ' Maxconn ': 33333333333}}]

Second, decomposition to achieve the above process:

  1 #!/usr/bin/env Python 2 #-*-coding:utf-8-*-3 #Author: Nulige 4 5 import OS 6 7 #def file_handle (file Name,backend_data,record_list=none,type= ' fetch '): 8 9 #实现查询功能 def fetch (data): Backend_data= "Backend%s"                             %data #backend www.oldboy1.org Find matching to this line, find the corresponding server record, using string concatenation method record_list=[]         #定义一个空列表 with open (' haproxy.conf ', ' R ') as F: #打开haproxy. conf configuration file Tag=false #报警器不响 16 For lines in F: #去查找文件 if line.strip () = = Backend_data: #把文件的每一行 \ n Remove to compare, find this line backend WWW.OLDBOY1.O RG Tag=true #找到人就响警报 Continue #就跳出这个循环 if tag and Line.startswith (' Backend '): #找到下一行的backend, backend www.oldboy2.org we'll jump out of the loop. If tag and line: #相当于警报 Rang Record_list.append (Line.strip ()) #找到了server 10.10.0.10 10.10.0.10 weight 9999 maxconn 33333333333, To add him to the list.Line in record_list:25 print (line) #给用户打印找到的信息 return record_list     #给用户返回处理的信息 def Add (data): backend=data[' backend ' Record_list=fetch (backend) 32                                                         Current_record = "Server%s%s weight%s maxconn%s"% (data[' record '] [' Server '], 33 data[' record ' [' Server '], data[' record  ' [' weight '], data[' record ' [' Maxconn ']) Backend_data = "Backend%s"% backend PNs if not record_list:39 record_list.append (backend_data) record_list. Append (Current_record) with open (' haproxy.conf ', ' R ') as Read_file, and (' haproxy_new.conf ', '             W ') as write_file:43 for R_line in read_file:44 write_file.write (r_line) 45 46 For New_line in record_list:47 if New_line.startswith (' backend '): write_file.write (new_line+ ' \ n ') 49 Else:50 write_file.write ("%s%s\n"% (' *8,new_line) else:53 #处理recard_list record_list.insert (0,backend_data) Record_ List.append (Current_record) with open (' haproxy.conf ', ' R ') as Read_file, (' Haproxy_new.c Onf ', ' W ') as write_file:58 tag = False Has_write = False for R_line in Read_fil  e:61 if r_line.strip () = = backend_data:62 Tag = True continue If tag and r_line.startswith (' backend '): all tags = False if not                         tag:67 write_file.write (r_line) else:69 if not has_write:70                     For New_line in record_list:71        If New_line.startswith (' backend '): Write_file.write (new_line + ' \ n ') 73                         else:74 write_file.write ("%s%s\n"% (' * 8, New_line) 75 Has_write = True os.rename (' haproxy.conf ', ' haproxy_bak.conf ') os.rename (' haproxy_new.conf ', ' Haproxy.conf ') os.remove (' haproxy_bak.conf ') #{' backend ': ' lhf.oldboy.org ', ' record ': {' server ': ' 1.1.1.1 ', '      Weight ': 2, ' maxconn ': ' $ '} (Bayi) def remove (data): backend=data[' backend '] Record_list=fetch (backend) 86                                                         Current_record = "Server%s%s weight%s maxconn%s"% (data[' record '] [' Server '], 87 data[' record ' [' Server '], data[' Recor d ' [' Weight '], data[' record ' [' Maxconn ']) backend_data = "Backend%s"% backend Record_list and Current_record not in record_list:92 print (' \033[33:[1m no this record \033[0] ') Eturn 94 else:95 #处理recard_list Record_list.insert (0,backend_data) Record_list.remove (c Urrent_record) 98 with open (' haproxy.conf ', ' R ') as Read_file, in the open (' haproxy_new.conf ', ' W ') as                 write_file:100 Tag = False101 Has_write = False102 for r_line in read_file:103                 If R_line.strip () = = backend_data:104 Tag = True105 continue106                     If tag and r_line.startswith (' backend '): 107 tag = False108 if not tag:109                         Write_file.write (r_line) else:111 if not has_write:112                                 For new_line in record_list:113 if New_line.startswith (' backend '): 114 Write_file.write (new_line + ' \ n ') else:116 write_file.write ("%s% s\n "% (' * 8, New_line)) 117 Has_write = True118 os.rename (' haproxy.conf ', ' haproxy_bak.conf ') ) 119 Os.rename (' haproxy_new.conf ', ' haproxy.conf ') os.remove (' haproxy_bak.conf ') 121 122 #{' backend ': ' Www.oldboy1 . org11111 ', ' record ': {' server ': ' 11.100.200.1 ', ' weight ': +, ' maxconn ': 200}}123 124 def Change (data): 126 backend= data[0][' backend ' #找到要修改的第一条记录127 record_list=fetch (backend) Old_record = "Server%s%s weight%s Maxconn%s"                                                     % (data[0][' record '] [' Server '], 129 data[0][' record ' [' Server '], 130                                                     data[0][' record ' [' Weight '], 131 data[0][' record '] [' maxconn ']) 133 New_record = "Server%s%s weight%s maxconn%s"% (data[1][' record            ' [' Server '], 134                                         data[1][' record ' [' Server '], 135     data[1][' record ' [' weight '], 136 data[1][' record ' [' Maxconn ']) 137         Backend_data = "Backend%s"% backend138 if not record_list and Old_record not in Record_list: #判断这个文件在原文件中不存在139 Print (' \033[33:[1m no content \033[0] ') return141 else:142 record_list.insert (0,backend_data) #判 The 143 Index=record_list.index (Old_record) #求出这个索引144 Record_list[index]=new_record #用新的记录 in the original file for the broken file, Replace old records 145 with open (' haproxy.conf ', ' R ') as Read_file, 146 open (' haproxy_new.conf ', ' W ') as Write_fi                 le:147 Tag = False148 Has_write = False149 for r_line in read_file:150 If R_line.strip () = = backend_data:151 Tag = True152 continue153 I F tag and R_LINE.STARTSWITH (' backend '): 154 tag = False155 if not tag:156 write_file.write ( R_line) 157 else:158 if not has_write:159 for New_line in Recor d_list:160 if New_line.startswith (' backend '): 161 WRITE_FILE.WR ITE (new_line + ' \ n ') 162 else:163 write_file.write ("%s%s\n"% (     "* 8, New_line)) 164 Has_write = True165 os.rename (' haproxy.conf ', ' haproxy_bak.conf ') 166        Os.rename (' haproxy_new.conf ', ' haproxy.conf ') 167 os.remove (' haproxy_bak.conf ') 168 169 #backend www.oldboy2.org170 #server 3.3.3.3 3.3.3.3 weight maxconn 3000171 #[{' backend ': ' www.oldboy2.org ', ' record ': {' server ': ' 3.3.3.3 ', ' weight ': ' maxconn ': 3000}},{' backend ': ' www.oldboy2.org ', ' record ': {' server ': ' 10.10.10.10 ', ' weight ': ' Maxconn ' : 3000000}}]172 173 def exit (data): 174 pASS175 176 177 If __name__ = = ' __main__ ': #__name__是python的内置变量, he assigns __name__ __main__178 ' 179 1: Query 180 2: Add 181 3: Delete 182 4: Modify 183 5: Exit 184 "' 185 # define a dictionary, key corresponding to the FETCH function, others same 186 menu_dic={187 ' 1 '       : fetch,188 ' 2 ': add,189 ' 3 ': remove,190 ' 4 ': change,191 ' 5 ': exit,192}193 while True:         #死循环, constantly interacting with the user 194 print (msg) #打印出msg信息, allowing the user to select the menu 195 choice=input ("Operation >>:"). Strip () #去掉空格196 If len (choice) = = 0 or choice not in Menu_dic:continue #len (choice) ==0, judging if he is not empty, choice in the dictionary, jump out of this operation 197 if CH Oice = = ' 5 ': break198 199 data=input ("Data >>:"). Strip () #用户输入的是字符串200 201 #menu_dic [Choice] (data) ==fe TCH (data) 202 if choice! = ' 1 ': #如果输入的不是查询的话, you need to convert the string to a dictionary 203 data=eval (data) #因为添加和删除都要求是字典的形 Format, so we're going to convert the user input string into a dictionary 204 Menu_dic[choice] (data) #add (data)

PYTHON modifies the configuration file

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.