`

python文件操作

 
阅读更多

给一个配置文件

  用户输入字符串

  转换为字典

 

import json 

s=input(">>")

 

dic = json.loads(s)

type(dic)

 

backend 下server 下添加一条纪录

 

添加一条纪录 

  删除一条纪录

 

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 test.oldboy.org

        server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000

        server 100.1.7.9 100.1.7.999 weight 20 maxconn 3000

 

 

 

 

 

 

分享到:
评论
2 楼 xdx2599 2016-01-20  
#!/usr/bin/python
#  -*- coding: utf-8 -*-

import  json
import  copy
import os

# strings = '{"bakend": "www.oldboy.org","record":{"server": "100.1.7.99","weight": 20,"maxconn": 30}}'
# dict_info = json.loads(strings)
# dic_record = dict_info.get("record")
# addStrings = "server %s %s weight %d maxconn %d" % (dic_record.get("server"),dic_record.get("server"),dic_record.get("weight"),dic_record.get("maxconn"))


def myInput():
    try:
        strings = input(">>")
        dict_info = json.loads(strings)
        dic_record = dict_info.get("record")
        addStrings = "server %s %s weight %d maxconn %d" % (dic_record.get("server"),dic_record.get("server"),dic_record.get("weight"),dic_record.get("maxconn"))
        return  addStrings
    except Exception as err:
        print(err)
# print(addStrings)
#['server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000', 'server 100.1.7.999 100.1.7.999 weight 20 maxconn 3000']

# "server %s %s weight %d maxconn %d" % (dict_info['record']['server'], dict_info['record']['server'], dict_info['record']['weight'], dict_info['record']['maxconn'])

# print(dic_record)
# print(dic_record.get("server"))
filename="ha.conf"
title="backend"
contextflag="server"
addRecord = ""
controller = True
while(controller):
    try:
        addRecord=myInput()
        controller=False
    except Exception as err:
        print(err)
def fetch(filename,title,contextflag):
    record_list = []
    with open(filename) as obj:
        flag = False
        for line in obj:
            line = line.strip()
            if line.startswith(title):
                flag = True
                continue
            if flag and line.startswith(contextflag):
                record_list.append(line)
                continue
            else:
                flag = False
    return record_list
record_list = fetch(filename,title,contextflag)
new_list=copy.deepcopy(record_list)
# print(new_list.__contains__(addStrings))
if(new_list.__contains__(addRecord)):
    print("纪录已存在")
    exit()
new_list.append(addRecord)
# print(record_list.__len__())
# print(new_list)

with open(filename) as read_file, open('tmp', 'w') as write_file:
    lines = read_file.readlines()
    flag = False
    counter = 0
    for line in lines:
         line = line.strip()
         if line.startswith(title):
                write_file.writelines(line+"\n")
                flag = True
                continue
         if flag and line.startswith(contextflag):
             counter=counter+1
             if(counter==record_list.__len__()):
                 flag = False
                 for record in new_list:
                    write_file.writelines(record+"\n")
                 counter=0
             continue
         if flag and record_list.__len__()==0:
             write_file.writelines(new_list)
         write_file.writelines(line+"\n")
read_file.close()
write_file.close()
if os.path.exists("ha.bak"):
   os.remove("ha.bak")
os.rename('ha.conf','ha.bak')
os.rename('tmp','ha.conf')


1 楼 xdx2599 2016-01-20  
#!/usr/bin/python
#  -*- coding: utf-8 -*-

import  json
import  copy
import os

strings = '{"bakend": "www.oldboy.org","record":{"server": "100.1.7.99","weight": 20,"maxconn": 30}}'

dict_info = json.loads(strings)
dic_record = dict_info.get("record")
addStrings = "server %s %s weight %d maxconn %d" % (dic_record.get("server"),dic_record.get("server"),dic_record.get("weight"),dic_record.get("maxconn"))
# print(addStrings)
#['server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000', 'server 100.1.7.999 100.1.7.999 weight 20 maxconn 3000']

# "server %s %s weight %d maxconn %d" % (dict_info['record']['server'], dict_info['record']['server'], dict_info['record']['weight'], dict_info['record']['maxconn'])

# print(dic_record)
# print(dic_record.get("server"))
filename="ha.conf"
title="backend"
contextflag="server"
def fetch(filename,title,contextflag):
    record_list = []
    with open(filename) as obj:
        flag = False
        for line in obj:
            line = line.strip()
            if line.startswith(title):
                flag = True
                continue
            if flag and line.startswith(contextflag):
                record_list.append(line)
                continue
            else:
                flag = False
    return record_list
record_list = fetch(filename,title,contextflag)
new_list=copy.deepcopy(record_list)
new_list.append(addStrings)
print(record_list.__len__())
# print(new_list)

with open(filename) as read_file, open('tmp', 'w') as write_file:
    lines = read_file.readlines()
    flag = False
    counter = 0
    for line in lines:
         line = line.strip()
         if line.startswith(title):
                write_file.writelines(line)
                flag = True
                continue
         if flag and line.startswith(contextflag):
             counter=counter+1
             if(counter==record_list.__len__()):
                 flag = False
                 write_file.writelines(new_list)
                 counter=0
             continue
         if flag and record_list.__len__()==0:
             write_file.writelines(new_list)
         write_file.writelines(line)
read_file.close()
write_file.close()
if os.path.exists("ha.bak"):
   os.remove("ha.bak")
os.rename('ha.conf','ha.bak')
os.rename('tmp','ha.conf')


相关推荐

Global site tag (gtag.js) - Google Analytics