1. 程式人生 > >運維自動化之IPy模塊

運維自動化之IPy模塊

Python IPy

IPy模塊是用來處理IPv4和IPv6地址的網絡類工具

1.通過網段輸出該網段下的IP個數和IP清單

>>> from IPy import IP 
>>> ip = IP(‘192.168.1.0/29‘)
>>> ip.len()
8
>>> for x in ip:
...     print(x)
... 
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

2.IP版本,反向解析,IP類型,IP轉換等

>>> IP(‘10.0.0.0/8‘).version()
4   #IPv4版本
>>> IP(‘::1‘).version()
6   #IPv6版本
>>> from IPy import IP
>>> ip = IP(‘192.168.1.20‘)
>>> ip.reverseNames()   #反向解析地址
[‘20.1.168.192.in-addr.arpa.‘]
>>> ip.iptype()   
‘PRIVATE‘   #ip類型為私網類型
>>> IP(‘4.4.4.4‘).iptype()
‘PUBLIC‘   #公網類型
>>> IP(‘4.4.4.4‘).int()
67372036    #整型
>>> IP(‘4.4.4.4‘).strHex()
‘0x4040404‘   #十六進制
>>> IP(‘4.4.4.4‘).strBin()   #二進制
‘00000100000001000000010000000100‘
>>> print(IP(0x4040404))   #將十六進制轉換成IP格式
4.4.4.4

3. 網絡地址的轉換

>>> IP(‘127.0.0.0/8‘)
IP(‘127.0.0.0/8‘)
>>> IP(‘127.0.0.0/255.0.0.0‘)
IP(‘127.0.0.0/8‘)
>>> IP(‘127.0.0.0-127.255.255.255‘)
IP(‘127.0.0.0/8‘)
>>> from IPy import IP
>>> print(IP(‘192.168.1.0/255.255.255.0‘,make_net=True))
192.168.1.0/24
>>> print(IP(‘192.168.1.0‘).make_net(‘255.255.255.0‘))
192.168.1.0/24
>>> 

4. 定制要轉換的地址為字符串

輸出格式介紹:

wantprefixlen == 0 / None     don‘t return anything   1.2.3.0
wantprefixlen == 1            /prefix                 1.2.3.0/24
wantprefixlen == 2            /netmask                1.2.3.0/255.255.255.0
wantprefixlen == 3            -lastip                 1.2.3.0-1.2.3.255

使用strNormal方法指定不同wantprefixlen參數來定制輸出不同類型的網段:

>>> IP(‘192.168.1.0/24‘).strNormal()
‘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‘

5.多網絡計算方法:

通常用來比較兩個網段是否存在重疊。

1.判斷IP地址和網段是否包含在另一個網段中.

>>> ‘192.168.1.100‘ in IP(‘192.168.1.0/24‘)
True
>>> IP(‘192.168.1.0/24‘) in IP(‘192.168.0.0/16‘)
True

2.判斷兩個網段是否存在重疊。使用overlaps方法。

>>> IP(‘192.168.0.0/23‘).overlaps(‘192.168.1.0/24‘)
1  #1代表存在重疊
>>> IP(‘192.168.0.0/23‘).overlaps(‘192.168.2.0‘)
0   #0代表不存在重疊

附上簡單的Python程序:根據輸入的IP或子網返回網絡、 掩碼、 廣播、反向解析、子網數、 IP類型等信息。

#!/usr/bin/python
#--*-- coding:utf-8 --*--
#filename:show_ip.py
#author:dianel
#2018.3.26 17:20:23

from IPy import IP

def main():
        ip_s = raw_input("Please enter IP:")
        ip = IP(ip_s)
        if ip.len() > 1:
                print(‘net is: %s‘ %ip.net())
                print(‘netmask: %s‘ %ip.netmask())
                print(‘broadcast: %s‘ %ip.broadcast())
                print(‘reverse address: %s‘ %ip.reverseNames()[0])
                print(‘subnet: %s‘ %len(ip))
        else:
                print(‘reverses address: %s‘ %ip.reverseNames()[0])
                print(‘version: %s‘ %ip.version())
                print(‘iptype: %s‘ %ip.iptype())
                print(‘hexadecimal: %s‘ %ip.strHex())
if __name__ == ‘__main__‘:
        main()

運維自動化之IPy模塊