我需要对包含IP地址的文件执行whois查找,并将国家/地区代码和IP地址输出到新文件中。到目前为止,在我的命令中,我找到了IP地址并获得了一个与允许范围不匹配的唯一副本。然后我运行一个whois查找以找出外国地址是谁。最后它将国家代码拉出来。这很好用,但我无法通过国家代码向我显示IP,因为它不包含在whois输出中。
在输出中包含IP地址的最佳方法是什么?
awk '{match($0,/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/); ip = substr($0,RSTART,RLENGTH); print ip}' myInputFile \
| sort \
| uniq \
| grep -v '66.33\|66.128\|75.102\|216.106\|66.6' \
| awk -F: '{ print "whois " $1 }' \
| bash \
| grep 'country:' \
>> myOutputFile
我曾考虑过使用tee,但是在以合理的方式排列数据方面遇到了麻烦。输出文件应包含IP地址和国家/地区代码。如果它们是单列或双列,则无关紧要。
以下是一些示例输入:
Dec 27 04:03:30 smtpfive sendmail [14851]:tBRA3HAx014842:to =,delay = 00:00:12,xdelay = 00:00:01,mailer = esmtp,pri = 1681345,relay = redcondor.itctel 。C OM。 [75.102.160.236],dsn = 4.3.0,stat =延期:451本次超出收件人限额 的nDer 12月27日04:03:30 smtpfive sendmail [14851]:tBRA3HAx014842:to =,delay = 00:00:12,xdelay = 00:00:01,mailer = esmtp,pri = 1681345,relay = redcondor.itctel.c OM。 [75.102.160.236],dsn = 4.3.0,stat =延期:451本次超出收件人限额 的nDer
感谢。
答案 0 :(得分:2)
一般来说:将输入作为shell变量进行迭代;然后,您可以将它们与shell的每个输出一起打印出来。
以下内容适用于bash 4.0或更新版本(需要关联数组):
#!/bin/bash
# ^^^^- must not be /bin/sh, since this uses bash-only features
# read things that look vaguely like IP addresses into associative array keys
declare -A addrs=( )
while IFS= read -r ip; do
case $ip in 66.33.*|66.128.*|75.102.*|216.106.*|66.6.*) continue;; esac
addrs[$ip]=1
done < <(grep -E -o '[0-9]+[.][0-9]+[.][0-9]+[.][0-9]+')
# getting country code from whois for each, printing after the ip itself
for ip in "${!addrs[@]}"; do
country_line=$(whois "$ip" | grep -i 'country:')
printf '%s\n' "$ip $country_line"
done
备用版本,可以使用旧的(3.x)版本的bash,使用sort -u
生成唯一值,而不是在shell内部执行:
while read -r ip; do
case $ip in 66.33.*|66.128.*|75.102.*|216.106.*|66.6.*) continue;; esac
printf '%s\n' "$ip $(whois "$ip" | grep -i 'country:')"
done < <(grep -E -o '[0-9]+[.][0-9]+[.][0-9]+[.][0-9]+' | sort -u)
为整个脚本执行输入和输出重定向比在>>
本身之后放置printf
重定向更高效(这会在每次打印操作之前打开文件,然后再次关闭它,导致性能损失很大),这就是为什么建议的脚本调用看起来像这样:
countries_for_addresses </path/to/logfile >/path/to/output