1. 程式人生 > >001_自定義過濾及添加文件內容腳本(nginx)

001_自定義過濾及添加文件內容腳本(nginx)

parser sys idt fin rip readlines pat utf default

一、工作中遇到sed添加及修改在nginx末尾添加太麻煩了

需求:隨意查找添加一條以前不存在的內容加到"}"前一行

技術分享

實現:

#!/usr/bin/env python
# coding=utf-8
import sys,os
from optparse import OptionParser

parse = OptionParser()
parse.add_option("-c", "--context", help="add one line contexts",default="xxxhtxxxtps_status")
parse.add_option("-f", "--file", help="modify file",default="/006_eleallproject/002_surveypro/001_nginxdevops/002_camel-agent-deploy/camel-agent-deploy2.0/nginx.conf")

(options, args) = parse.parse_args()
content = options.context
file = os.path.realpath(options.file)
#content="x$https_status"
#file=‘/006_eleallproject/002_surveypro/001_nginxdevops/002_camel-agent-deploy/camel-agent-deploy2.0/nginx.conf‘
print options


_list_content=[]
m = 0
count = 0
#獲取"}"的位置
try:
    fh = open(file, ‘rb‘)
    for n in fh.readlines():
        m += 1
        if (n.find(‘}‘) >= 0):
            global count
            count = m
            _list_content.append(n)
        else:
            _list_content.append(n)
finally:
    fh.close()


#在"}"位置前添加內容
n = 0
ngconf = open(file, ‘rb‘)
for s in ngconf.readlines():
    n += 1
    if s.find(‘}‘) >= 0 and n >= count-1:
        #在以前的列表中有任何可以找到的內容都不會添加
        result = any([str(line.strip()).find(content) >=0  for line in  _list_content])
        if not result:
            _list_content.insert(count-1, content+"\n")
ngconf.close()


#寫入文件
end_nginx_f = open(file, ‘wb‘)
end_nginx_f.writelines(_list_content)
end_nginx_f.close()

  

001_自定義過濾及添加文件內容腳本(nginx)