49 lines
1.4 KiB
Python
49 lines
1.4 KiB
Python
|
# coding: utf-8
|
||
|
|
||
|
import re
|
||
|
import os
|
||
|
from netaddr import *
|
||
|
|
||
|
|
||
|
class Detect(object):
|
||
|
def __init__(self):
|
||
|
self.iplist = list()
|
||
|
|
||
|
def list_bridges(self):
|
||
|
return os.popen('ifconfig').read()
|
||
|
|
||
|
def detect(self, ip_for_vm):
|
||
|
ip4vm = IPAddress(ip_for_vm)
|
||
|
c = list()
|
||
|
for paragraph in self.list_bridges().split('\n\n'):
|
||
|
|
||
|
# ma = re.compile("(br\d+).*HWaddr ([^ ]+).*addr:([^ ]+).*Mask:([^ ]+)", re.MULTILINE | re.DOTALL)
|
||
|
ma = re.compile("(virbr\d+|br\d+|br\d:\d+) .*HWaddr ([^ ]+).*addr:([^ ]+).*Mask:([^ ]+)", re.MULTILINE | re.DOTALL)
|
||
|
|
||
|
result = ma.match(paragraph)
|
||
|
|
||
|
if result:
|
||
|
vlan = result.group(1).rstrip()
|
||
|
mac = result.group(2).rstrip()
|
||
|
ip = result.group(3).rstrip()
|
||
|
mask = result.group(4).rstrip()
|
||
|
|
||
|
# inrange
|
||
|
ip.split('.')
|
||
|
|
||
|
m = mac.split(':')
|
||
|
mac = m[0] + m[1] + "." + m[2] + m[3] + "." + m[4] + m[5]
|
||
|
|
||
|
# print "vlan:", vlan
|
||
|
# print "ip:",ip
|
||
|
# print "mac:", mac
|
||
|
ipn = IPNetwork(ip, mask)
|
||
|
|
||
|
c.append(dict(interface=vlan, ip=ip, mask=mask, mac=mac, valid=True if ip4vm in ipn else False))
|
||
|
return c
|
||
|
|
||
|
def get_suitable_interface(self, ip):
|
||
|
for interface in self.detect(ip):
|
||
|
if interface['valid']:
|
||
|
return interface['interface']
|