zoukankan      html  css  js  c++  java
  • 001_自定义过滤及添加文件内容脚本(nginx)

    一、工作中遇到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+"
    ")
    ngconf.close()
    
    
    #写入文件
    end_nginx_f = open(file, 'wb')
    end_nginx_f.writelines(_list_content)
    end_nginx_f.close()
    

      

  • 相关阅读:
    rpm 和 yum 的使用技巧
    启动Hadoop时遇到Name or service not knownstname 错误
    使用Pod集成Bugtags填坑记
    xcode 上 crash 调试的三种方法
    在MAC上安装虚拟机搭建Ubuntu开发环境
    shell复习---文件解压命令
    XCODE7新变化之-test
    Object-C单元测试&MOCK(摘录精选)
    shell复习笔记----查找与替换
    shell复习笔记----命令与参数
  • 原文地址:https://www.cnblogs.com/arun-python/p/7153562.html
Copyright © 2011-2022 走看看