本文整理汇总了Python中netaddr.valid_mac函数的典型用法代码示例。如果您正苦于以下问题:Python valid_mac函数的具体用法?Python valid_mac怎么用?Python valid_mac使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了valid_mac函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: find_from_tuple
def find_from_tuple(cls, link):
"""
Find link by providing a tuple with two ip addresses or two mac addresses
:param link: tuple with two string elements indicating source and destination (ip or mac addresses)
:returns: Link object
"""
try:
a = link[0]
b = link[1]
except IndexError:
raise ValueError('Expecting tuple with source and destination')
# find interfaces
if (valid_ipv4(a) and valid_ipv4(b)) or (valid_ipv6(a) and valid_ipv6(b)):
try:
a = Ip.objects.get(address=a).interface
b = Ip.objects.get(address=b).interface
except Ip.DoesNotExist as e:
raise LinkDataNotFound(e)
elif valid_mac(a) and valid_mac(b):
try:
a = Interface.objects.get(mac=a)
b = Interface.objects.get(mac=b)
except Interface.DoesNotExist as e:
raise LinkDataNotFound(e)
else:
raise ValueError('Expecting valid ipv4, ipv6 or mac address')
# find link with interfaces
# inverse order is also ok
q = Q(interface_a=a, interface_b=b) | Q(interface_a=b, interface_b=a)
link = Link.objects.filter(q).first()
if link is None:
raise LinkNotFound('Link matching query does not exist',
interface_a=a,
interface_b=b)
return link
示例2: validate
def validate(value):
try:
netaddr.valid_mac(value)
except netaddr.AddrFormatError:
error = 'value should be MAC format.'
raise ValueError(error)
else:
return value
示例3: check_config
def check_config(self):
super(DP, self).check_config()
test_config_condition(not isinstance(self.dp_id, int), (
'dp_id must be %s not %s' % (int, type(self.dp_id))))
test_config_condition(self.dp_id < 0 or self.dp_id > 2**64-1, (
'DP ID %s not in valid range' % self.dp_id))
test_config_condition(not netaddr.valid_mac(self.faucet_dp_mac), (
'invalid MAC address %s' % self.faucet_dp_mac))
test_config_condition(not (self.interfaces or self.interface_ranges), (
'DP %s must have at least one interface' % self))
# To prevent L2 learning from timing out before L3 can refresh
test_config_condition(self.timeout < self.arp_neighbor_timeout, (
'L2 timeout must be >= ARP timeout'))
if self.cache_update_guard_time == 0:
self.cache_update_guard_time = int(self.timeout / 2)
if self.learn_jitter == 0:
self.learn_jitter = int(max(math.sqrt(self.timeout) * 3, 1))
if self.learn_ban_timeout == 0:
self.learn_ban_timeout = self.learn_jitter
if self.lldp_beacon:
self._check_conf_types(self.lldp_beacon, self.lldp_beacon_defaults_types)
test_config_condition('send_interval' not in self.lldp_beacon, (
'lldp_beacon send_interval not set'))
test_config_condition('max_per_interval' not in self.lldp_beacon, (
'lldp_beacon max_per_interval not set'))
self.lldp_beacon = self._set_unknown_conf(
self.lldp_beacon, self.lldp_beacon_defaults_types)
if self.lldp_beacon['system_name'] is None:
self.lldp_beacon['system_name'] = self.name
if self.stack:
self._check_conf_types(self.stack, self.stack_defaults_types)
if self.dot1x:
self._check_conf_types(self.dot1x, self.dot1x_defaults_types)
self._check_conf_types(self.table_sizes, self.default_table_sizes_types)
示例4: validate_config
def validate_config(options):
config = ConfigParser.ConfigParser()
config.readfp(options.config)
if not config.has_section(options.env):
error("Environment {} does not exist in file {}".format(options.env, options.config.name))
env = dict(config.items(options.env))
if not valid_mac(env["fuel_mac"]):
error("Wrong MAC address for Fuel node: {}".format(env["fuel_mac"]))
for key in ["fuel_ip", "fuel_netmask", "fuel_gw", "fuel_control_ip"]:
if not valid_ipv4(env[key]):
error("Wrong IP address ({}) for {} parameter".format(env[key], key))
ip = IPNetwork(env["fuel_ip"] + "/" + env["fuel_netmask"])
gw = IPAddress(env["fuel_gw"])
if gw not in ip:
error("Gateway address is not within network range")
for path in [
env["image_mount_dir"],
env["ks_files_dir"],
env["ks_patch"],
env["pxe_config_dir"],
env["esxi_private_key_file"],
]:
if not os.path.exists(path):
error("Path {} does not exist or is not accessible".format(path))
env["pxe_config_file"] = os.path.join(env["pxe_config_dir"], "01-{}".format(env["fuel_mac"].replace(":", "-")))
return env
示例5: __post_load_macs
def __post_load_macs(self):
"""
Called by post_load() to load internal representation of macs
"""
self.macs = self.link_data('macs', dict)
for k, v in self.macs.items():
old_k = k
k = k.lower()
if netaddr.valid_mac(k) is False:
self.app.log.error("data:mac: Invalid key format '{}: File {}".format(k, self.path))
continue
if v is not None:
v = v.lower()
if netaddr.valid_mac(k) is False:
self.app.log.error("data:mac: Invalid value format '{}: File {}".format(k, self.path))
continue
del self.macs[old_k]
self.macs[k] = v
示例6: _validate_mac_address
def _validate_mac_address(data, valid_values=None):
try:
valid_mac = netaddr.valid_mac(_validate_no_whitespace(data))
if valid_mac is False:
msg = _("'%s' is not a valid MAC address") % data
LOG.debug(msg)
return msg
except AttributeError as ex:
msg = _("MAC address must be string: %s") % ex
LOG.exception(msg)
return msg
示例7: test_list_virtual_interfaces
def test_list_virtual_interfaces(self):
# Positive test:Should be able to GET the virtual interfaces list
# for a given server_id
resp, output = self.client.list_virtual_interfaces(self.server_id)
self.assertEqual(200, resp.status)
self.assertNotEqual(output, None)
virt_ifaces = output
self.assertNotEqual(0, len(virt_ifaces["virtual_interfaces"]), "Expected virtual interfaces, got 0 interfaces.")
for virt_iface in virt_ifaces["virtual_interfaces"]:
mac_address = virt_iface["mac_address"]
self.assertTrue(netaddr.valid_mac(mac_address), "Invalid mac address detected.")
示例8: test_list_virtual_interfaces
def test_list_virtual_interfaces(self):
# Positive test:Should be able to GET the virtual interfaces list
# for a given server_id
output = self.client.list_virtual_interfaces(self.server_id)
self.assertIsNotNone(output)
virt_ifaces = output
self.assertNotEqual(0, len(virt_ifaces['virtual_interfaces']),
'Expected virtual interfaces, got 0 interfaces.')
for virt_iface in virt_ifaces['virtual_interfaces']:
mac_address = virt_iface['mac_address']
self.assertTrue(netaddr.valid_mac(mac_address),
"Invalid mac address detected.")
示例9: _validate_mac_address
def _validate_mac_address(data, valid_values=None):
try:
valid_mac = netaddr.valid_mac(_validate_no_whitespace(data))
except Exception:
valid_mac = False
# TODO(arosen): The code in this file should be refactored
# so it catches the correct exceptions. _validate_no_whitespace
# raises AttributeError if data is None.
if not valid_mac:
msg = _("'%s' is not a valid MAC address") % data
LOG.debug(msg)
return msg
示例10: validate_mac_address
def validate_mac_address(data, valid_values=None):
try:
valid_mac = netaddr.valid_mac(validate_no_whitespace(data))
except Exception:
valid_mac = False
if valid_mac:
valid_mac = (not netaddr.EUI(data) in
map(netaddr.EUI, constants.INVALID_MAC_ADDRESSES))
# TODO(arosen): The code in this file should be refactored
# so it catches the correct exceptions. validate_no_whitespace
# raises AttributeError if data is None.
if not valid_mac:
msg = _("'%s' is not a valid MAC address") % data
LOG.debug(msg)
return msg
示例11: check_config
def check_config(self):
super(VLAN, self).check_config()
test_config_condition(not self.vid_valid(self.vid), 'invalid VID %s' % self.vid)
test_config_condition(not netaddr.valid_mac(self.faucet_mac), (
'invalid MAC address %s' % self.faucet_mac))
test_config_condition(
self.acl_in and self.acls_in, 'found both acl_in and acls_in, use only acls_in')
if self.acl_in and not isinstance(self.acl_in, list):
self.acls_in = [self.acl_in,]
self.acl_in = None
if self.acls_in:
for acl in self.acls_in:
test_config_condition(
not isinstance(acl, (int, str)), 'acl names must be int or str')
if self.max_hosts:
if not self.proactive_arp_limit:
self.proactive_arp_limit = 2 * self.max_hosts
if not self.proactive_nd_limit:
self.proactive_nd_limit = 2 * self.max_hosts
if self.faucet_vips:
self.faucet_vips = frozenset([
self._check_ip_str(ip_str, ip_method=ipaddress.ip_interface)
for ip_str in self.faucet_vips])
if self.routes:
test_config_condition(not isinstance(self.routes, list), 'invalid VLAN routes format')
try:
self.routes = [route['route'] for route in self.routes]
except TypeError:
raise InvalidConfigError('%s is not a valid routes value' % self.routes)
except KeyError:
pass
for route in self.routes:
test_config_condition(not isinstance(route, dict), 'invalid VLAN route format')
test_config_condition('ip_gw' not in route, 'missing ip_gw in VLAN route')
test_config_condition('ip_dst' not in route, 'missing ip_dst in VLAN route')
ip_gw = self._check_ip_str(route['ip_gw'])
ip_dst = self._check_ip_str(route['ip_dst'], ip_method=ipaddress.ip_network)
test_config_condition(
ip_gw.version != ip_dst.version,
'ip_gw version does not match the ip_dst version')
self.add_route(ip_dst, ip_gw)
示例12: test_list_virtual_interfaces
def test_list_virtual_interfaces(self):
# Positive test:Should be able to GET the virtual interfaces list
# for a given server_id
if CONF.service_available.neutron:
with testtools.ExpectedException(exceptions.BadRequest):
self.client.list_virtual_interfaces(self.server['id'])
else:
output = self.client.list_virtual_interfaces(self.server['id'])
virt_ifaces = output['virtual_interfaces']
self.assertNotEmpty(virt_ifaces,
'Expected virtual interfaces, got 0 '
'interfaces.')
for virt_iface in virt_ifaces:
mac_address = virt_iface['mac_address']
self.assertTrue(netaddr.valid_mac(mac_address),
"Invalid mac address detected. mac address: %s"
% mac_address)
示例13: serialize
def serialize(self, _payload=None, _prev=None):
opt_buf = bytearray()
if self.options is not None:
opt_buf = self.options.serialize()
if netaddr.valid_mac(self.chaddr):
chaddr = addrconv.mac.text_to_bin(self.chaddr)
else:
chaddr = self.chaddr
self.hlen = len(chaddr)
return struct.pack(self._DHCP_PACK_STR, self.op, self.htype, self.hlen,
self.hops, self.xid, self.secs, self.flags,
addrconv.ipv4.text_to_bin(self.ciaddr),
addrconv.ipv4.text_to_bin(self.yiaddr),
addrconv.ipv4.text_to_bin(self.siaddr),
addrconv.ipv4.text_to_bin(self.giaddr),
chaddr,
self.sname.encode('ascii'),
self.boot_file.encode('ascii')) + opt_buf
示例14: get
def get(self, mac, full):
"""
json response from www.macvendorlookup.com:
{u'addressL1': u'1 Infinite Loop',
u'addressL2': u'',
u'addressL3': u'Cupertino CA 95014',
u'company': u'Apple',
u'country': u'UNITED STATES',
u'endDec': u'202412195315711',
u'endHex': u'B817C2FFFFFF',
u'startDec': u'202412178538496',
u'startHex': u'B817C2000000',
u'type': u'MA-L'}
"""
unknown = {'company': 'unknown'}
if not valid_mac(mac):
print('Error: the mac addr {} is not valid'.format(mac))
return
try:
r = requests.get('http://www.macvendorlookup.com/api/v2/' + mac)
except requests.exceptions.HTTPError as e:
print ("HTTPError:", e.message)
return unknown
if r.status_code == 204: # no content found, bad MAC addr
print ('ERROR: Bad MAC addr:', mac)
return unknown
elif r.headers['content-type'] != 'application/json':
print ('ERROR: Wrong content type:', r.headers['content-type'])
return unknown
a = {}
try:
if full: a = r.json()[0]
else: a['company'] = r.json()[0]['company']
# print 'GOOD:',r.status_code,r.headers,r.ok,r.text,r.reason
except:
print ('ERROR:', r.status_code, r.headers, r.ok, r.text, r.reason)
a = unknown
return a
示例15: test_list_virtual_interfaces
def test_list_virtual_interfaces(self):
# Positive test:Should be able to GET the virtual interfaces list
# for a given server_id
if CONF.service_available.neutron:
# TODO(mriedem): After a microversion implements the API for
# neutron, a 400 should be a failure for nova-network and neutron.
with testtools.ExpectedException(exceptions.BadRequest):
self.client.list_virtual_interfaces(self.server['id'])
else:
output = self.client.list_virtual_interfaces(self.server['id'])
virt_ifaces = output
self.assertNotEmpty(virt_ifaces['virtual_interfaces'],
'Expected virtual interfaces, got 0 '
'interfaces.')
for virt_iface in virt_ifaces['virtual_interfaces']:
mac_address = virt_iface['mac_address']
self.assertTrue(netaddr.valid_mac(mac_address),
"Invalid mac address detected. mac address: %s"
% mac_address)