您的位置:首页 > 编程语言 > Python开发

Python自动化运维笔记(二):Python中的IP地址处理模块IPy的使用

2017-09-23 15:46 507 查看
该博文多数参考于运维偶像级人物刘天斯所著《Python自动化运维-技术与最佳实践》一书

环境:
Python 3.6


前言

Python提供了一个强大的第三方模块
IPy
下载链接),用于计算IP地址,包括网段、子网掩码、广播地址、子网数、IP类型等等。目前最新版本为
v0.83
,文档介绍支持
Python2.6-3.4
,在实际使用中我是用的
Python3.6
运行没有出现异常。

基本处理

① 查看IP类型,IP个数,IP地址清单

from IPy import IP
ip_temp = "192.168.1.0/24"
ip = IP(ip_temp)
print("%s 的IP个数为%d" % (ip_temp,ip.len()))
print('类型为:IPv%s' % ip.version())
for x in ip:
print(x)


运行结果:

192.168.1.0/24 的IP个数为256

类型为:IPv4

192.168.1.0

192.168.1.1

192.168.1.2

192.168.1.3

192.168.1.4

192.168.1.5

192.168.1.6

192.168.1.7

......


② IP进制转换,网络地址转换

IP类型以及进制的转换

>>> IP('8.8.8.8').iptype()      # IP地址类型,8.8.8.8为公网IP
'PUBLIC'
>>> IP('8.8.8.8').int()         # 转换成整数类型
134744072
>>> IP('8.8.8.8').strBin()      # 转换成二进制类型
'00001000000010000000100000001000'
>>> IP('8.8.8.8').strHex()      # 转换成16进制类型
'0x8080808'


网络地址的转换

可以实现网络地址的转换,例如根据IP与掩码生产网段格式。

>>> from IPy import IP
>>> 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.1' in IP('192.168.1.0/24')
True
>>> IP('192.168.1.0/24') in IP('192.168.0.0/16')
True


判断两个网段是否存在重叠,采用IPy提供的
overlaps
方法


>>> IP('192.168.0.0/23').overlaps('192.168.1.0/24')
1           # 存在重叠
>>> IP('192.168.1.0/24').overlaps('192.168.2.0')
0           # 不存在重叠


示例代码

# coding:utf-8
# 代码来源:《Python自动化运维-技术与最佳实践》刘天斯著.P10
# 根据输入的IP或子网返回网络、掩码、广播、反向解析、子网数、IP类型等信息

from IPy import IP

ip_input = input("please input an IP or net-range: ")
ips = IP(ip_input)

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: %s' % ips.strBin())              # 输出二进制地址
print('iptype: %s' % ips.iptype())              # 输出地址类型(私网、公网、环回地址)


运行结果:

输入地址为:192.168.1.1时:
please input an IP or net-range: 192.168.1.1
reverse address: 1.1.168.192.in-addr.arpa.
hexadecimal: 0xc0a80101
binary: 11000000101010000000000100000001
iptype: PRIVATE
输入地址为:192.168.1.0/28时:
please input an IP or net-range: 192.168.1.0/28
net: 192.168.1.0
netmask: 255.255.255.240
broadcast: 192.168.1.15
reverse address: 0.1.168.192.in-addr.arpa.
subnet: 16
hexadecimal: 0xc0a80100
binary: 11000000101010000000000100000000
iptype: PRIVATE
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: