考试题目-红绿灯编辑文件

文件:

listen stats:8888
    stats enable
    stats uri   /admin
    stats auth  admin:1234

backend www.oldboy.org
    server 100.1.7.9 100.1.7.9 weight20 maxconn 3000
    server 100.1.7.8 100.1.7.8 weight20 maxconn 3000
    server 100.1.7.7 100.1.7.7 weight20 maxconn 3000

backend buy.oldboy.org
    server 100.1.7.90 100.1.7.90 weight20 maxconn 3000

 

 

 

 

 1 #!/usr/bin/evn python
 2 #-*- coding:utf-8 -*-
 3 import json
 4 def fetch(backend):
 5     f = '绿灯'
 6     result = []
 7     with open('ha.conf','r') as f:
 8         for line in f:
 9             if(line.strip()) == 'backend %s'%backend:
10 
11                 f= '红灯'
12                 continue
13 
14             if f == '红灯':
15                 if line.strip().startswith('backend'):
16                     f = '绿灯'
17                 else:
18                     if line.strip():
19                         result.append(line.strip())
20     return result
21 
22 
23 def add(backend,record):
24     record_list = fetch(backend)
25     record_list.append(record)
26 
27     print(record_list)
28     f = '绿灯'
29     with open('ha.conf','r') as f1, open('hb.conf','w') as f2:
30         for line in  f1:
31             if line.strip() == 'backend %s'%backend:
32                 f = '红灯'
33                 f2.write(line)
34                 for newline in record_list:
35                     f2.write(' '*8+newline+'\n')
36                 continue
37             if f == '绿灯':
38                 f2.write(line)
39             else:
40                 if line.strip().startswith('backend'):
41                     f = '绿灯'
42                     f2.write(line)
43 
44 
45 # inp = input('请输入')
46 # ret = fetch('www.oldboy.org')
47 # print(ret)
48 dicts = '{"backend":"www.oldboy.org","record":{"server":"100.1.7.6","weight":20,"maxconn":30}}'
49 dic = json.loads(dicts)
50 bk = dic['backend']
51 rd = 'server %s %s weight %d maxconn %d' %(dic['record']['server'],
52                                                dic['record']['server'],
53                                                dic['record']['weight'],
54                                                dic['record']['maxconn'])
55 #
56 # add('{"backend":"www.oldboy.org","record":{"server":"100.1.7.6","weight":20,"maxconn":30}}')
57 
58 
59 add(bk,rd)

 

posted @ 2016-06-18 22:26  咖啡茶  阅读(94)  评论(0)    收藏  举报