Python 3:从CIDR表示法创建可能的IP地址列表

问题描述 投票:10回答:7

我已经完成了在python(3.1)中创建一个函数的任务,该函数将采用CIDR表示法并返回可能的ip地址列表。我查看了python.org并发现了这个:http://docs.python.org/dev/py3k/library/ipaddr.html

但我还没有看到任何可以满足这种需求的东西......我会非常感激任何人都愿意帮助我的方式。提前致谢。 :-)

python subnet cidr
7个回答
35
投票

如果您没有使用内置模块,那么有一个名为netaddr的项目,它是我用于处理IP网络的最佳模块。

看看IP Tutorial,它说明了它如何轻松地与网络协作并识别其IP。简单的例子:

>>> from netaddr import IPNetwork
>>> for ip in IPNetwork('192.0.2.0/23'):
...    print '%s' % ip
...
192.0.2.0
192.0.2.1
192.0.2.2
192.0.2.3
...
192.0.3.252
192.0.3.253
192.0.3.254
192.0.3.255

10
投票

在Python 3中就像

>>> import ipaddress
>>> [str(ip) for ip in ipaddress.IPv4Network('192.0.2.0/28')]
['192.0.2.0', '192.0.2.1', '192.0.2.2',
'192.0.2.3', '192.0.2.4', '192.0.2.5',
'192.0.2.6', '192.0.2.7', '192.0.2.8',
'192.0.2.9', '192.0.2.10', '192.0.2.11',
'192.0.2.12', '192.0.2.13', '192.0.2.14',
'192.0.2.15']

9
投票

我宁愿做一些数学而不是安装一个外部模块,没有人和我有同样的味道?

#!/usr/bin/env python
# python cidr.py 192.168.1.1/24

import sys, struct, socket

(ip, cidr) = sys.argv[1].split('/')
cidr = int(cidr) 
host_bits = 32 - cidr
i = struct.unpack('>I', socket.inet_aton(ip))[0] # note the endianness
start = (i >> host_bits) << host_bits # clear the host bits
end = start | ((1 << host_bits) - 1)

# excludes the first and last address in the subnet
for i in range(start, end):
    print(socket.inet_ntoa(struct.pack('>I',i)))

1
投票

你检查过iptools吗?这似乎是一个相当不错的选择。


0
投票

它不在文档中,但浏览源代码表明ipaddr实现了__iter__iterhosts,这正是你想要的。


呃,没关系。

  1. 看起来ipaddr.py在3.1 beta中添加到stdlib,但是被3.1 rc删除了。
  2. 我正在查看原始ipaddr.py的来源,它似乎与python.org上的副本分开进化。

你可以捆绑后者。


0
投票

下面的代码将生成提供IP和子网的IP范围。展开CIDR表示法,如(255.255.255.0)

from netaddr import *

def getFirstIp(ipAddress,subnet):
  ipBin = IPNetwork(ipAddress).ip.bits().split('.')
  subBin = IPNetwork(subnet).ip.bits().split('.')
  zipped = zip(ipBin,subBin)
  netIdList = []
  for octets in zipped:
    netIdList.append(''.join(str(b) for b in (map((lambda x: int(x[0])*int(x[1])),zip(list(octets[0]),list(octets[1]))))))
  firstIp = ''
  firstIp = '.'.join(str(int(oct,2)) for oct in netIdList)
  return firstIp


def getLastIp(ipAddress,subnet):
  ipBin = IPNetwork(ipAddress).ip.bits().split('.')
  subBin = IPNetwork(subnet).ip.bits().split('.')
  #print ipBin
  #print subBin
  revsubBin = []
  for octets in subBin:
    revB = ''.join('1' if(b == '0') else '0' for b in octets)
    revsubBin.append(revB)
  zipped = zip(ipBin,revsubBin)
  netIdList = []
  for octets in zipped:
    netIdList.append(''.join(str(b) for b in (map((lambda x: 0 if(int(x[0]) == 0 and int(x[1]) == 0) else 1),zip(list(octets[0]),list(octets[1]))))))
  #print netIdList
  lastIp = ''
  lastIp = '.'.join(str(int(oct,2)) for oct in netIdList)
  return lastIp

def getRangeOfIps(firstIp,lastIp):
  start= int(IPAddress(firstIp))
  end = int(IPAddress(lastIp))
  ipList = []
  for ip in range(start,end+1):
    ipList.append(str(IPAddress(ip)))
  return ipList

def manipulateIP():
 firstIp = getFirstIp(ipAddress,subnet)
 lastIp = getLastIp(ipAddress,subnet)
 ipList = getRangeOfIps(firstIp,lastIp)  
 print ipList 

0
投票

Generate all Public IP Addresses given a CIDR

https://github.com/stephenlb/geo-ip将生成包括地点在内的有效IP公共地址列表。

'1.0.0.0/8''191.0.0.0/8'是有效的公共IP地址范围,不包括保留的专用IP地址。

IP Generator

生成IP地址和关联的地理信息的JSON转储。请注意,有效的公共IP地址范围是从'1.0.0.0/8''191.0.0.0/8',不包括本自述文件中较低的保留的专用IP地址范围。

docker build -t geo-ip .
docker run -e IPRANGE='54.0.0.0/30' geo-ip               ## a few IPs
docker run -e IPRANGE='54.0.0.0/26' geo-ip               ## a few more IPs
docker run -e IPRANGE='54.0.0.0/16' geo-ip               ## a lot more IPs
docker run -e IPRANGE='0.0.0.0/0'   geo-ip               ## ALL IPs ( slooooowwwwww )
docker run -e IPRANGE='0.0.0.0/0'   geo-ip > geo-ip.json ## ALL IPs saved to JSON File
docker run geo-ip 

扫描所有有效公共地址的速度更快一些:

for i in $(seq 1 191); do \
    docker run -e IPRANGE="$i.0.0.0/8" geo-ip; \
    sleep 1; \ 
done

这会向STDOUT打印少于4,228,250,625个JSON行。以下是其中一行的示例:

{"city": "Palo Alto", "ip": "0.0.0.0", "longitude": -122.1274,
 "continent": "North America", "continent_code": "NA",
 "state": "California", "country": "United States", "latitude": 37.418,
 "iso_code": "US", "state_code": "CA", "aso": "PubNub",
 "asn": "11404", "zip_code": "94107"}

专用和保留IP范围

上面的repo中的dockerfile将根据维基百科文章的指南排除不可用的IP地址:https://en.wikipedia.org/wiki/Reserved_IP_addresses

MaxMind Geo IP

dockerfile导入https://www.maxmind.com/en/home提供的免费公共数据库

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