程序1: 实现简单的shell sed替换功能
import os,sys
old = sys.argv[1]
new = sys.argv[2]
file_name = sys.argv[3]
tmp_file ="tmpfile"
open(tmp_file,"w")
file1 = open(file_name,"r")
file2 = open(tmp_file,"r+")
for line in file1:
if old in line:
line= str.replace(line,old,new)
file2.write(line)
if new not in line:
file2.write(line)
file2.flush()
file1.close()
file2.close()
os.remove(file_name)
os.rename(tmp_file,file_name)
程序2:修改haproxy配置文件
import os
def select(backend):
result = []
flag = False
with open("haproxy.conf","r",encoding="UTF-8") as f:
for line in f:
if line.strip() == "backend %s" %(backend):
flag = True
continue
if line.strip().startswith("backend"):
flag = False
if flag:
line = line.strip()
result.append(line)
for i in result:
if i == "":
result.remove(i)
for i in result:
print(i)
return i
def append(backend):
with open("haproxy.conf","a",encoding="UTF-8") as f:
f.write("%sbackend %s%s%8sserver %s %s weight %s maxconn %s"%(" ",backend[0]," ","",backend[1],backend[1],backend[2],backend[3]))
def delete(backend):
file1 = open("haproxy.conf","r",encoding="UTF-8")
file2 = open("haproxy.new","w+",encoding="UTF-8")
flag = False
for line in file1:
if backend in line:
flag = True
continue
elif flag:
flag = False
else:
file2.write(line)
file1.close()
file2.close()
os.remove("haproxy.conf")
os.renames("haproxy.new","haproxy.conf")
def update(backend,select):
print("您要修改的是:%s"%(select))
delete(backend)
backend=[]
backend_message = input("例:www.baidu.com 192.168.1.1 200 2000 请输入修改后的新信息:")
append(backend_message.split(" "))
if __name__ == "__main__":
while True:
print(u"%s 1.查找记录 2.添加记录 3.删除记录 4.修改记录 5.退出程序 "%("".center(50,"-")))
case=int(input("case input number:"))
if case == 2:
backend=[]
backend_message = input("例:www.baidu.com 192.168.1.1 200 2000 请输入相关信息:")
append(backend_message.split(" "))
elif case == 1:
select(input("例:www.baidu.com 请输入要查找的backend:"))
elif case == 3:
delete(input("例:www.baidu.com 请输入要删除的backend:"))
elif case == 4:
backend=input("例:www.baidu.com 请输入要修改的backend:")
update(backend,select(backend))
elif case == 5:
exit("已经退出程序")
else:
print("