参数:-i,-ip,–ip,-n,-netmask,–netmaskpython ipAddressLearning.py -i 10.180.210.21/24
python ipAddressLearning.py -i 10.180.210.21 -n 255.255.240.0
# -*- coding:utf-8 -*-
"""
根据输入网段或ip+netmask获取网段详细信息
网段:192.168.120.12/24
ip:192.168.120.12
netmast:255.255.255.0
"""
import sys
import getopt
import ipaddress
from IPy import IP
def checkip(ip):
"""判断输入是否合法"""
try:
ipaddress.ip_address(ip)
return True
except ValueError:
pass
try:
ipaddress.ip_network(ip, strict=False)
return True
except ValueError:
pass
print('{0} is not a valid IP address'.format(ip))
return False
def valid_ip(ip):
"""判断ip或子网掩码是否合法"""
try:
# 判断 python 版本
if sys.version_info[0] == 2:
ipaddress.ip_address(ip.strip().decode("utf-8"))
elif sys.version_info[0] == 3:
ipaddress.ip_address(ip.strip())
return True
except Exception as e:
print("非法ip地址:{0}".format(ip))
return False
def ip_info(ip_net):
"""输出ip网段所包含的信息"""
try:
net = ipaddress.ip_network(ip_net, strict=False)
print('IP版本号: ' + str(net.version))
print('是否是私有地址: ' + str(net.is_private))
print('IP地址总数: ' + str(net.num_addresses))
print('可用IP地址总数: ' + str(len([x for x in net.hosts()])))
print('网络号: ' + str(net.network_address))
print('广播地址: ' + str(net.broadcast_address))
print('起始可用IP地址: ' + str([x for x in net.hosts()][0]))
print('最后可用IP地址: ' + str([x for x in net.hosts()][-1]))
print('可用IP地址范围: ' + str([x for x in net.hosts()][0]) + ' ~ ' + str([x for x in net.hosts()][-1]))
print('掩码地址: ' + str(net.netmask))
print('反掩码地址: ' + str(net.hostmask))
except ValueError:
print('您输入格式有误,请检查!')
def ip_net(ipaddr, ipnetmask):
"""根据ip地址ipaddr和子网掩码ipnetmask,获取ip网段"""
return IP(ipaddr).make_net(ipnetmask).strNormal()
if __name__ == '__main__':
ipaddr = None
ipnetmask = None
# 从输入中获取数据
opts, args = getopt.getopt(sys.argv[1:], '-i:-n:', ['ip=', 'netmask='])
for opt_name, opt_value in opts:
if opt_name in ('-i', '-ip', '--ip'):
ipaddr = opt_value
if opt_name in ('-n', '-netmask', '--netmask'):
ipnetmask = opt_value
if checkip(ipaddr) or checkip(ipnetmask):
if '/' in ipaddr:
ip_info(ipaddr)
elif valid_ip(ipaddr) and valid_ip(ipnetmask):
ip_net_res = ip_net(ipaddr, ipnetmask)
ip_info(ip_net_res)
参考:https://docs.python.org/3.7/howto/ipaddress.html
来源:CSDN
作者:@TangXin
链接:https://blog.csdn.net/Happy_Sunshine_Boy/article/details/103596957