nginx梳理脚本

NGINX梳理脚本

在这个脚本中,我们假设您的 Nginx 配置文件都存放在同一个目录下(在target_directory中指定),并且这些配置文件都以.conf扩展名结尾。脚本会使用每个配置文件,提取其中的指令和参数,并输出到控制台。

请确保将target_directory替换为您实际的配置文件所在目录。

这只是一个简单的示例,实际上,您可能需要根据您的具体情况对脚本进行更多的定制和改进。例如,您可以考虑处理包含指令的情况,处理蚀刻块,实现更高级的分析和报告功能等。

#! /usr/bin/python3

import os

def extract_directives(file_path):
    directives = []
    with open(file_path, 'r') as f:
        lines = f.readlines()
        for line in lines:
            line = line.strip()
            if line.startswith('#') or not line:
                continue
            parts = line.split()
            directive = parts[0]
            arguments = parts[1:] if len(parts) > 1 else []
            directives.append((directive, arguments))
    return directives

def analyze_config_files(directory):
    config_files = [f for f in os.listdir(directory) if f.endswith('.conf')]
    result = {}
    
    for file_name in config_files:
        file_path = os.path.join(directory, file_name)
        directives = extract_directives(file_path)
        result[file_name] = directives
    
    return result

def main():
    target_directory = '/apps/nginx/conf.d'
    analysis_result = analyze_config_files(target_directory)
    
    for file_name, directives in analysis_result.items():
        print(f"Directives in {file_name}:")
        for directive, arguments in directives:
            print(f"  {directive}: {arguments}")

if __name__ == '__main__':
    main()
    

进入脚本所在的目录:使用cd命令切换到配置脚本的目录。假设已将脚本保存为nginx_config_analyzer.py,并且脚本和要分析的 Nginx 配置文件都在同一个目录下。
验证,如图所示:
在这里插入图片描述