如何以只能从文本文件中获取所需单词的方式使用 grep?

How to use grep in way, where I can only get the word I want from a textfile?

我正在尝试使用 grep /var/log/secure 来查找尝试使用我的实例的唯一 IP 地址。每次,我都尝试 grep 获取 IP 所在的行。我怎样才能以一种只获取所需 IP 并将其存储在文本文件中的方式进行 grep。我将 post 示例来阐明我在寻找什么。

This is a sample /var/log/secure file:

Oct  9 22:45:48 ip-172-26-14-23 sshd[18080]: Disconnected from 34.101.251.82 port 59344 [preauth]
Oct  9 22:46:41 ip-172-26-14-23 sshd[18082]: Did not receive identification string from 209.17.97.18 port 64550
Oct  9 22:47:23 ip-172-26-14-23 sshd[18083]: Connection closed by 74.120.14.52 port 44578 [preauth]
Oct  9 22:54:03 ip-172-26-14-23 sshd[18088]: Invalid user cisco from 106.13.233.5 port 44180
Oct  9 22:54:03 ip-172-26-14-23 sshd[18088]: input_userauth_request: invalid user cisco [preauth]
Oct  9 22:54:03 ip-172-26-14-23 sshd[18088]: Received disconnect from 106.13.233.5 port 44180:11: Bye Bye [preauth]
Oct  9 22:54:03 ip-172-26-14-23 sshd[18088]: Disconnected from 106.13.233.5 port 44180 [preauth]
Oct  9 22:56:53 ip-172-26-14-23 sshd[18090]: reverse mapping checking getaddrinfo for reaia.tumblles.com [141.98.9.32] failed - POSSIBLE BREAK-IN ATTEMPT!
Oct  9 22:56:54 ip-172-26-14-23 sshd[18090]: Connection closed by 141.98.9.32 port 34537 [preauth]
Oct  9 22:56:57 ip-172-26-14-23 sshd[18092]: reverse mapping checking getaddrinfo for kei.tumblles.com [141.98.9.33] failed - POSSIBLE BREAK-IN ATTEMPT!

所以我想要的是 grep var/log/secure 并只打印试图在文本文件中使用我的实例的唯一 ips,如下所示:

**Desired output:**
34.101.251.82
74.120.14.52
106.13.233.5
141.98.9.32
So on....
I might have missed some but you get the idea.

当我尝试使用以下命令对文件进行 grep 时:sudo grep 'from' /var/log/secure | awk {print } > ips.out. 我在文件中得到以下输出。

9
9
9
9
9
9
9
so on....

9 是日期 输入背后的意识形态是“来自”这个词紧挨着 ip 地址。所以 grep 应该去那里并用 awk{print $2} 打印下一个词。

但是,我想从文件中的任何地方提取所有 IPS,而不仅仅是“from”之后的 IPS。我上面所做的是目前我能做到的唯一方法。我正在考虑 运行 多个命令并制作一个 bash 从所有位置获取 Ips 的脚本。

PS: 我只想要 from!

之后的 IP

你可以使用 grep 的正向后视来做到这一点,你必须对 Perl-compatible 正则表达式使用 -P,而且 -o 只打印匹配的字符串。

> grep -Po "(?<=from )[0-9]{1,3}(\.[0-9]{1,3}){3}" file
34.101.251.82 
209.17.97.18 
106.13.233.5 
106.13.233.5 
106.13.233.5 

括号内的开头部分“from ”将首先匹配,但对于-o选项将被忽略,仅考虑后面的部分。

这部分是匹配IP的简单表达式,意思是:

[0-9]{1,3}     (\.       [0-9]{1,3}) {3}
1-3 digits and (dot with 1-3 digits) {3 times more}

这是 4 个数字,最多 3 位,用点分隔。

详细了解如何将 IP 匹配到此 question

仅基于显示的示例,请您尝试按照以下内容编写和测试link https://ideone.com/bQGspU

awk '
BEGIN{
  FS="from[[:space:]]+|[[:space:]]+port"
}
~/^[0-9]{1,3}(\.[0-9]{1,3}){3}$/{
  print 
}
' Input_file

使用 GNU awk multi-char RS

awk -v RS="[0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}" 'RT{print RT}' file

34.101.251.82
209.17.97.18
74.120.14.52
106.13.233.5
106.13.233.5
106.13.233.5
141.98.9.32
141.98.9.32
141.98.9.33
141.98.9.33

并且 uniq 命令删除了相邻的重复行

$ awk -v RS="[0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}" 'RT{print RT}' file | uniq
34.101.251.82
209.17.97.18
74.120.14.52
106.13.233.5
141.98.9.32
141.98.9.33