Fork me on GitHub

day3

程序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"%("\n",backend[0],"\n","\b",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\n请输入修改后的新信息:")
append(backend_message.split(" "))

if __name__ == "__main__":
while True:
print(u"%s\n1.查找记录\n2.添加记录\n3.删除记录\n4.修改记录\n5.退出程序\n"%("".center(50,"-")))
case=int(input("case input number:"))
if case == 2:
backend=[]
backend_message = input("例:www.baidu.com 192.168.1.1 200 2000\n请输入相关信息:")
append(backend_message.split(" "))
elif case == 1:
select(input("例:www.baidu.com\n请输入要查找的backend:"))
elif case == 3:
delete(input("例:www.baidu.com\n请输入要删除的backend:"))
elif case == 4:
backend=input("例:www.baidu.com\n请输入要修改的backend:")
update(backend,select(backend))
elif case == 5:
exit("已经退出程序")
else:
print("\033[1;31;47m请输入正确case指令\033[0m")
 
 





posted @ 2016-10-28 12:35  Anonymous-develop  阅读(169)  评论(0编辑  收藏  举报

python自动化开发&研究 - 创建于 2016年1月10日

这是一位运维自动化开发工程师的个人站,内容主要是网站开发方面的技术文章,大部分来自学习或工作,部分来源于网络,希望对大家有所帮助。

致力于自动化应用开发&研究工作,专注运维与前端开发,关注互联网前沿技术与趋势。


廖雪峰的博客 | 徐亮的博客 | 刘耀的博客 | python基础课程 | 我的svn | 我的个人导航首页