在Linux中搜索文件以匹配IP地址 [英] Search file for matching IP address in Linux

查看:285
本文介绍了在Linux中搜索文件以匹配IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个分配了IP地址范围的文件.看起来像这样:

I have file with allocated IP address ranges. It looks something like this:

...
arin|US|ipv4|8.0.0.0|16777216|19921201|allocated
arin|US|ipv4|9.0.0.0|16777216|19881216|assigned
apnic|ID|ipv4|122.200.144.0|2048|20061023|allocated
apnic|TW|ipv4|122.200.152.0|2048|20080424|allocated
apnic|AU|ipv4|122.200.160.0|4096|20061020|allocated
apnic|AU|ipv4|122.200.176.0|4096|20110121|allocated
apnic|JP|ipv4|122.200.192.0|8192|20061023|allocated
...

我的问题是,是否可能以及如何使用grep,awk等工具在Linux中使用IP地址作为搜索参数从该文件中获取特定行.

My question is if it is possible and how to get specific row from this file using an IP address as search parameter in Linux by using tools like grep, awk or some other tools.

例如如果搜索到的IP为8.8.8.8,则结果应为:

e.g. if the searched IP is 8.8.8.8 the result should be:

arin|US|ipv4|8.0.0.0|16777216|19921201|allocated

编辑//完整的ipv4列表可在此处找到 http://skechboy.com/ips/ipv4_table

EDIT// FUll ipv4 list can be found here http://skechboy.com/ips/ipv4_table

推荐答案

如果第4列和第5列是网络前缀和子网掩码,然后为IP输入grep:

if 4th and 5th columns are network prefix and subnet mask then to grep input for an ip:

#!/usr/bin/env python
import fileinput, socket, struct, sys

# x.x.x.x string -> integer
ip2int = lambda ipstr: struct.unpack('!I', socket.inet_aton(ipstr))[0]    

ip = ip2int(sys.argv.pop(1)) # get ip from command-line
for line in fileinput.input(): # read from stdin or file(s) given at command-line
    try:
        family, network_prefix, subnet_mask = line.split('|')[2:5]
        if (family == 'ipv4' and
            (ip & (2**32 - int(subnet_mask))) == ip2int(network_prefix)):
            print line,
    except Exception:
        print >>sys.stderr, "can't parse", line,

示例

$ python grep-ip.py 192.168.5.193 <<'.'
x|x|ipv4|192.168.5.128|64|x|x
x|x|ipv4|192.168.5.192|64|x|x
x|x|ipv4|192.168.5.0|64|x|x
x|x|ipv4|192.168.5.0|256|x|x
.

输出

x|x|ipv4|192.168.5.192|64|x|x
x|x|ipv4|192.168.5.0|256|x|x

这篇关于在Linux中搜索文件以匹配IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆