python中IP处理模块IPy

1、安装

pip install IPy

2、IP地址、网段的基本处理

>>> IP('10.0.0.1').version()
4
>>> IP('::1').version()
6
>>> ip=IP('192.168.0.0/16')
>>> print ip.len()
65536
>>> for x in ip:
...     print x
192.168.36.158
192.168.36.159
192.168.36.160
192.168.36.161
192.168.36.162
192.168.36.163
192.168.36.164
192.168.36.165
192.168.36.166
192.168.36.167
192.168.36.168
192.168.36.169
192.168.36.170
192.168.36.171
192.168.36.172
192.168.36.173
192.168.36.174
192.168.36.175
192.168.36.176

3、常见用法

>>> ip = IP('192.168.10.20')
>>> ip.reverseNames()
['20.10.168.192.in-addr.arpa.']
>>> ip.iptype()
'PRIVATE'
>>> IP('8.8.8.8').iptype()
'PUBLIC'
>>> IP('8.8.8.8').int()
134744072
>>> IP('8.8.8.8').strHex()
'0x8080808'
>>> IP('8.8.8.8').strBin()
'00001000000010000000100000001000
>>> print(IP('0x8080808'))
8.8.8.8
>>> print(IP('192.168.1.0').make_net('255.255.255.0'))
192.168.1.0/24
>>> print(IP('192.168.1.0/255.255.255.0',make_net=True))
192.168.1.0/24
>>> print(IP('192.168.1.0-192.168.1.255',make_net=True))
192.168.1.0/24
>>> IP('192.168.1.0/24').strNormal(0)
'192.168.1.0'
>>> IP('192.168.1.0/24').strNormal(1)
'192.168.1.0/24'
>>> IP('192.168.1.0/24').strNormal(2)
'192.168.1.0/255.255.255.0'
>>> IP('192.168.1.0/24').strNormal(3)
'192.168.1.0-192.168.1.255'
wantprefixlen的取值及含义:
wantprefixlen=0,无返回,如192.168.1.0
wantprefixlen=1,prefix格式,如192.168.1.0/24
wantprefixlen=2,decimalnetmask格式,如192.168.1.0/255.255.255.0
wantprefixlen=3,lastIP格式,如192.168.1.0-192.168.1.2554

4、多网络计算方法

1)IP比较
>>> IP('10.9.1.0/24') < IP('10.9.2.0/24')
True
2)IP地址和网络是否包含于另一个网段中
>>> IP('10.9.1.0/24') < IP('10.9.2.0/24')
True
>>> '192.168.2.100' in IP('192.168.2.0/24')
True
>>> '192.168.1.0/24' in IP('192.168.0.0/24')
False
>>> '192.168.1.0/24' in IP('192.168.0.0/16')
True
3)判断网络是否存在重叠
>>> IP('192.168.0.0/23').overlaps('192.168.1.0/24')
1  #返回1代表存在重叠
>>> IP('192.168.1.0/24').overlaps('192.168.2.0/24')
0 #返回0代表不存在重叠

5、IPy模块使用示例:

#!/bin/python
# _*_ coding:utf-8 _*_
from IPy import IP

ip_s = raw_input("please input an IP or net-range:")
ips = IP(ip_s)
if len(ips) > 1:
    print('net:%s' % ips.net()) #输出网络地址
    print('netmask:%s' % ips.netmask()) #输出网络掩码地址
    print('broadcast:%s' % ips.broadcast())#输出网络广播地址
    print('reverse address:%s' % ips.reverseNames()[0]) #输出地址反向解析
    print('subnet:%s' % len(ips))
else:
    print('reverse address:%s' % ips.reverseNames()[0]) #输出IP反向地址解析

print('hexadecimal:%s' % ips.strHex()) #输出十六进制地址
print('binary ip:%s' % ips.strBin()) #输出二进制地址
print('iptype:%s' % ips.iptype()) #输出地址类型

官方参考文档:http://github.com/haypo/python-ipy

猜你喜欢

转载自blog.csdn.net/qq_21127151/article/details/80140367
今日推荐