day2 文件实例
程序1: 实现简单的shell sed替换功能
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
old = input('你要修改原来的内容:') new = input('输入修改后的内容:') with open('old','r',encoding='utf-8') as f,\ open('new','a',encoding='utf-8') as f1:#old旧的文件,new新的文件 for line in f: if old in line: line = line.replace(old,new) f1.write(line)#将替换后的内容写入新文件
程序2:修改haproxy配置文件
配置文件:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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.7.9 100.1.7.9 weight 20 maxconn 3000
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# Author Cathy current_index = -1 dict_all = {} old_content = [] #将backend下的内容找到,并且变成字典的形式 with open("haproxy","r",encoding='utf-8') as f: for index,line in enumerate(f): if line.startswith("backend"):#判断是否是以backend为开头的 current_index = index + 1#将下标置为0 nod = line.strip().split()[1]#将'backend www.oldboy.org'转换成列表,并且删除前后的空格,以中间空格分成列表,nod为www.oldboy.org dict_all["backend"] = nod#生成一个{'bakend': 'www.oldboy.org'}字典 elif index == current_index: dict_all["record"] = {} dict_all["record"]["server"] = line.strip().split()[1],line.strip().split()[2] dict_all["record"]["weight"] = line.strip().split()[4] dict_all["record"]["maxconn"] = line.strip().split()[6] else: old_content.append(line.strip()) print('以下功能可使用:\n1.查询\n2.修改\n3.删除\n4.退出\n') flag = True while flag: option = int(input('请输入功能编号:')) #查询 if option == 1: backend_1 = input('请输入你要查询baclend下的节点:') for line in dict_all: if backend_1 in dict_all[line]: print(dict_all) else: continue #修改 elif option == 2: backend_2 = input('请输入你要修改baclend下的节点:') dict_all["backend"]= backend_2 dict_all["record"] = {} dict_all["record"]["server"] = input('输入server:') dict_all["record"]["weight"] = input('输入weight:') dict_all["record"]["maxconn"] = input('输入maxconn:') #删除 elif option ==3: backend_3 = input('请输入你要删除baclend下的节点:') if backend_3 == dict_all['backend']: dict_all= {} print("删除成功!") else: print("没有这个节点,重新输入!") elif option == 4: for i in old_content: f = open("haproxy_new", "a") f.write("%s\n"%i) if dict_all != {}: open("haproxy_new", "a").write("backend %s\n\tserver%s weight %s maxconn %s\n\n" % ( dict_all["backend"], dict_all["record"]["server"], dict_all["record"]["weight"], dict_all["record"]["maxconn"])) f.close() flag = False else: pass