You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
calculate-utils-3-lib/pym/utils/ip.py

168 lines
5.3 KiB

#-*- coding: utf-8 -*-
# Copyright 2008-2010 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import math
from cl_utils import process, checkUtils, readFile, listDirectory
import sys
import re
from os import path
import cl_lang
tr = cl_lang.lang()
tr.setLocalDomain('cl_lib')
tr.setLanguage(sys.modules[__name__])
# ip digit from 0|1-255|254 (template)
IP_DIG = "[%s-9]|(?:1[0-9]|[1-9])[0-9]|2[0-4][0-9]|25[0-%s]"
# ip net 0-32
IP_NET_SUFFIX = "[0-9]|[12][0-9]|3[012]"
# ip digs 1-254,0-254,0-255
IP_DIGS = { 'dig1_254' : IP_DIG % (1,4), 'dig0_254' : IP_DIG % (0,4),
'dig0_255' : IP_DIG % (0,5), }
# ip addr 10.0.0.12
IP_ADDR = "(%(dig1_254)s)\.(%(dig0_254)s)\.(%(dig0_254)s)\.(%(dig1_254)s)"%\
IP_DIGS
IP_MASK = "(%(dig0_255)s)\.(%(dig0_255)s)\.(%(dig0_255)s)\.(%(dig0_255)s)"%\
IP_DIGS
# ip addr for net 10.0.0.0
IP_NET = "(%(dig1_254)s)\.(%(dig0_254)s)\.(%(dig0_254)s)\.(%(dig0_254)s)"%\
IP_DIGS
# ip and net 192.168.0.0/16
IP_ADDR_NET = "(%(ipaddr)s)/((%(ipnet)s))"%{'ipaddr':IP_NET,
'ipnet':IP_NET_SUFFIX}
reIp = re.compile("^{0}$".format(IP_ADDR))
reNetSuffix = re.compile("^{0}$".format(IP_NET_SUFFIX))
reNet = re.compile("^{0}$".format(IP_ADDR_NET))
reMask = re.compile("^{}$".format(IP_MASK))
def checkIp(ip):
"""Check ip"""
return reIp.match(ip)
def checkNetSuffix(netSuffix):
"""Check net suffix"""
return reNetSuffix.match(netSuffix)
def checkNet(net):
"""Check net"""
if not reNet.match(net):
return False
mask = strIpToIntIp(netToMask(int(net)))
ip,op,net = net.partition('/')
return (strIpToIntIp(ip)&mask) == (strIpToIntIp(ip))
maskDigs = map(lambda x:str(x),(0b10000000,0b11000000,0b11100000,0b11110000,
0b11111000,0b11111100,0b11111110,0b11111111))
def checkMask(mask):
"""Check net"""
if mask.count('.') != 3:
return False
zero = False
for dig in mask.split('.'):
if zero or not dig in maskDigs:
if dig == "0":
zero = True
else:
return False
return True
def getIpAndMask(interface="eth0"):
"""Get ip and mask from interface"""
ifconfig = process('/sbin/ifconfig',interface)
res = re.search(r"inet addr:(\S+)\s.*Mask:(\S+)",ifconfig.read(),re.S)
if res:
return res.groups()
else:
return ("","")
def strIpToIntIp(addr):
"""Convert ip specified by string to integer"""
addr = addr.split('.')
return ((int(addr[0])<<24)|
(int(addr[1])<<16)|
(int(addr[2])<<8)|
(int(addr[3])))
return reduce(lambda x,y:x+(int(y[1])<<(y[0]*8)),
enumerate(reversed(addr.split("."))),0)
def intIpToStrIp(addr):
"""Convert ip specified by integer to string"""
return "{0}.{1}.{2}.{3}".format(
addr>>24,(addr>>16)&0xff,(addr>>8)&0xff,addr&0xff)
def maskToNet(mask):
"""Convert mask specified by str to net"""
mask = strIpToIntIp(mask)
return 32-int(math.log(((~mask) & 0xffffffff)+1,2))
def netToMask(net):
"""Convert net to mask specified by str"""
return intIpToStrIp((2**net-1)<<(32-net))
def getIpNet(ip,mask):
"""Get net (xx.xx.xx.xx/xx) by ip address and mask"""
ip = strIpToIntIp(ip)
net = maskToNet(mask)
mask = strIpToIntIp(mask)
return "{ip}/{net}".format(ip=intIpToStrIp(ip&mask),
net=net)
def isIpInNet(checkip,ipnet):
"""Check is ip in specified net"""
ip,op,net = ipnet.partition('/')
mask = strIpToIntIp(netToMask(int(net)))
return (strIpToIntIp(checkip)&mask) == (strIpToIntIp(ip)&mask)
def receiveMac(interface="eth0"):
"""Get MAC from interface"""
ipconfigProg = checkUtils('/sbin/ifconfig')
ifconfig = process(ipconfigProg,interface)
res = re.search(r"HWaddr\s(\S+)",ifconfig.read(),re.S)
if res:
return res.group(1)
else:
return "00:00:00:00:00:00"
def receiveIpAndMask(interface="eth0"):
"""Get ip and mask from interface"""
ipconfigProg = checkUtils('/sbin/ifconfig')
ifconfig = process(ipconfigProg,interface)
res = re.search(r"inet addr:(\S+)\s.*Mask:(\S+)",ifconfig.read(),re.S)
if res:
return res.groups()
else:
return ("","")
def isDhcpIp(interface="eth0"):
"""Get ip by dhcp or static"""
# dhclient
fdhcpLeases = "/var/lib/dhcp/dhclient.leases"
if interface in readFile(fdhcpLeases):
return True
# dhcpcd
fdhcpInfo = "/var/lib/dhcpcd/dhcpcd-%s.info"%interface
fdhcpLease = "/var/lib/dhcpcd/dhcpcd-%s.lease"%interface
if path.exists(fdhcpInfo) or path.exists(fdhcpLease):
return True
return False
def getInterfaces():
"""Get available interfaces"""
return filter(lambda x:x != "lo",
listDirectory('/sys/class/net'))