sed-包含“ |”运算符的捕获和打印正则表达式组

问题描述 投票:1回答:1

我有一个日志文件

...
Host: 111.222.121.123 (111.222.121.123.deploy.static.akamaitechnologies.com) Ports: 80/open/tcp//http//AkamaiGHost (Akamai's HTTP Acceleration|Mirror service)/, 443/open/tcp//ssl|http//AkamaiGHost (Akamai's HTTP Acceleration|Mirror service)/
Host: 1.2.3.4 ()  Ports: 80/open/tcp//http//cloudflare/, 443/open/tcp//ssl|https//cloudflare/, 2052/open/tcp//clearvisn?///, 2053/open/tcp//ssl|http//nginx/, 2082/open/tcp//infowave?///, 2083/open/tcp//ssl|http//nginx/, 2086/open/tcp//gnunet?///, 2087/open/tcp//ssl|http//nginx/, 2095/open/tcp//nbx-ser?///, 2096/open/tcp//ssl|http//nginx/, 8080/open/tcp//http-proxy//cloudflare/, 8443/open/tcp//ssl|https-alt//cloudflare/, 8880/open/tcp//cddbp-alt?///
...

我需要提取IP和http端口并将其转换为以下格式

1.2.3.4:80,443,2083

日志文件中只有两种类型的port字段

80/open/tcp//http
2083/open/tcp//ssl|http

尝试使用sed,但没有成功。我最终遇到了这个功能不正常的命令

cat ../host_ports.txt | sed -rn 's/Host: ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}).*?([0-9]{1,5}\/open\/tcp\/\/http|[0-9]{1,5}\/open\/tcp\/\/ssl\|http).*/\1 \2/p'
linux bash parsing sed nmap
1个回答
0
投票

此脚本将为您完成,您不需要sed:

#! /bin/bash

while read -r line
do
    host=$(echo "$line" | grep -Po '(?<=^Host: )[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+')
    ports=$(echo "$line" | grep -Po '[0-9]*((?=\/open\/tcp\/\/http\/)|(?=\/open\/tcp\/\/ssl\|http\/))' | tr '\n' ',')
    echo "$host:${ports:0:-1}" 
done < log

第一个grep将在Look behind的帮助下捕获IP地址。 -P用于像正则表达式一样使用perl,-o仅用于输出匹配的字符串

第二个正则表达式与第一个正则表达式非常相似,但是使用了后照而不是后面看。它只会捕获后面跟着/open/tcp//http//open/tcp//ssl|http/的端口。后面的tr将用逗号替换换行符。

${ports:0:-1}只是为了消除尾随逗号。

希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.