查找 IP 地址的日志 [英] Grepping logs for IP addresses
问题描述
我不擅长使用基本?"unix 命令和这个问题使我的知识更加需要测试.我想做的是从日志中获取所有 IP 地址(例如来自 apache 的 access.log)并计算它们发生的频率.我可以用一个命令来做到这一点,还是需要为此编写一个脚本?
I am quite bad at using "basic?" unix commands and this question puts my knowledge even more to test. What I would like to do is grep all IP adresses from a log (e.g. access.log from apache) and count how often they occur. Can I do that with one command or do I need to write a script for that?
推荐答案
你至少需要一个短管道.
You'll need a short pipeline at least.
sed -e 's/([0-9]+.[0-9]+.[0-9]+.[0-9]+).*$/1/' -e t -e d access.log | sort | uniq -c
这将打印每个 IP(尽管只适用于 ipv4),以计数为前缀进行排序.
Which will print each IP (will only work with ipv4 though), sorted prefixed with the count.
我用 apache2 的 access.log 对其进行了测试(不过它是可配置的,所以你需要检查),它对我有用.它假设 IP 地址是每一行的第一件事.
I tested it with apache2's access.log (it's configurable though, so you'll need to check), and it worked for me. It assumes the IP-address is the first thing on each line.
sed 收集 IP 地址(实际上它查找 4 组数字,中间有句点),并用它替换整行.-e t
如果它设法进行替换,则继续到下一行,-e d
删除该行(如果上面没有 IP 地址).sort
sorts.. :) 并且 uniq -c
计算连续相同行的实例(因为我们已经对它们进行了排序,所以对应于总计数).
The sed collects the IP-addresses (actually it looks for 4 sets of digits, with periods in between), and replaces the entire line with it. -e t
continues to the next line if it managed to do a substitution, -e d
deletes the line (if there was no IP address on it). sort
sorts.. :) And uniq -c
counts instances of consecutive identical lines (which, since we've sorted them, corresponds to the total count).
这篇关于查找 IP 地址的日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!