d代码:
# __author__ = liukun # coding:utf-8 line = input("please input the config :") #提示输入字符 #输入{"backend":"www.oldboy.org","record":{"server":"100.1.70.9","weight":20,"maxconm":3000}} a_dict = eval(line)#转换为字典 dict_b = a_dict['record'] line_b = a_dict['backend'] file_Read = open("config")#打开配置文件 file_Write = open("config.bak", 'w')#打开临时文件 file_test = file_Read.readline()#按行读取配置文件 while ('' != file_test): line = file_test.split() if line.count('backend') == 1 and line.count(a_dict['backend']) == 1 : #匹配域名所在行 file_Write.write(' ' + file_test) string = "server %s weight %s maxconn %s" %(dict_b['server'], dict_b['weight'],dict_b['maxconm']) #写入值太长,先用变量格式化. file_Write.write(' '*2 + string + ' ')#添加 两个tab保持缩进对齐,末尾换行 file_test = file_Read.readline() else: file_Write.write(file_test) file_test = file_Read.readline() file_Read.close() file_Write.close()#遍历完毕,关闭文件 file_Read_2 = open("config.bak") #将 bak 文件内容回写源文件 config file_Write_2 = open("config", 'w') file_test_2 = file_Read_2.readline() while ('' != file_test_2): file_Write_2.write(file_test_2) file_test_2 = file_Read_2.readline() file_Read_2.close() file_Write_2.close()
config:
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.70.9 weight 20 maxconn 31111 server 100.1.70.9 weight 20 maxconn 3000 server 100.1.70.9 weight 20 maxconn 3000 server 100.1.70.9 weight 20 maxconn 344444 server 100.1.70.9 weight 20 maxconn 3000 server 100.1.70.9 weight 20 maxconn 3000 server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000