从Apache配置文件提取主机名、虚拟IP、端口及日志目录
Apache配置文件提取FQDN、IP端口及日志目录解决方案
配置示例
<VirtualHost 192.168.1.10:80> ServerName www.example.com ServerAlias example.com DocumentRoot /var/www/example ErrorLog /var/log/apache2/example-error.log CustomLog /var/log/apache2/example-access.log combined </VirtualHost> <VirtualHost *:443> ServerName blog.example.com ServerAlias *.blog.example.com DocumentRoot /var/www/blog ErrorLog /var/log/apache2/blog-error.log CustomLog /var/www/blog-access.log combined </VirtualHost>
预期CSV输出
FQDN,IP,Port,LogDirectory www.example.com,192.168.1.10,80,/var/log/apache2 example.com,192.168.1.10,80,/var/log/apache2 blog.example.com,*,443,/var/log/apache2 *.blog.example.com,*,443,/var/log/apache2
需求一:关联FQDN与IP、端口
使用以下awk脚本,通过跟踪当前VirtualHost块的IP和端口,将其与ServerName/ServerAlias的FQDN关联:
BEGIN { FS = " " OFS = "," print "FQDN,IP,Port" } /^<VirtualHost/ { split($2, addr, ":") current_ip = addr[1] current_port = addr[2] next } /^[[:space:]]*Server(Name|Alias)/ { for (i=2; i<=NF; i++) { print $i, current_ip, current_port } }
运行方式:awk -f script.awk httpd.conf > output.csv
需求二:添加日志目录并解决awk数组错误
错误“attempt to use array `logs' in a scalar context”是因为将数组当作普通标量变量使用(比如直接引用数组名而非数组元素)。修正方案是用普通变量跟踪当前VirtualHost的日志目录,而非数组:
BEGIN { FS = " " OFS = "," print "FQDN,IP,Port,LogDirectory" } /^<VirtualHost/ { split($2, addr, ":") current_ip = addr[1] current_port = addr[2] current_log_dir = "" # 进入新虚拟主机时重置日志目录 next } /^[[:space:]]*ErrorLog/ { log_path = $2 sub(/\/[^\/]+$/, "", log_path) # 去掉文件名,保留目录 current_log_dir = log_path next } /^[[:space:]]*CustomLog/ { if (current_log_dir == "") { # 优先用ErrorLog,没有则用CustomLog log_path = $2 sub(/\/[^\/]+$/, "", log_path) current_log_dir = log_path } next } /^[[:space:]]*Server(Name|Alias)/ { for (i=2; i<=NF; i++) { print $i, current_ip, current_port, current_log_dir } }
运行方式:awk -f script_with_logs.awk httpd.conf > output_with_logs.csv
内容的提问来源于stack exchange,提问作者bubez
相关产品推荐
相关产品推荐

