Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/AnonR/anonr.TX.../opt/imh-pyth.../lib/python3....
File: uuid.py
r"""UUID objects (universally unique identifiers) according to RFC 4122.
[0] Fix | Delete
[1] Fix | Delete
This module provides immutable UUID objects (class UUID) and the functions
[2] Fix | Delete
uuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5
[3] Fix | Delete
UUIDs as specified in RFC 4122.
[4] Fix | Delete
[5] Fix | Delete
If all you want is a unique ID, you should probably call uuid1() or uuid4().
[6] Fix | Delete
Note that uuid1() may compromise privacy since it creates a UUID containing
[7] Fix | Delete
the computer's network address. uuid4() creates a random UUID.
[8] Fix | Delete
[9] Fix | Delete
Typical usage:
[10] Fix | Delete
[11] Fix | Delete
>>> import uuid
[12] Fix | Delete
[13] Fix | Delete
# make a UUID based on the host ID and current time
[14] Fix | Delete
>>> uuid.uuid1() # doctest: +SKIP
[15] Fix | Delete
UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')
[16] Fix | Delete
[17] Fix | Delete
# make a UUID using an MD5 hash of a namespace UUID and a name
[18] Fix | Delete
>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
[19] Fix | Delete
UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')
[20] Fix | Delete
[21] Fix | Delete
# make a random UUID
[22] Fix | Delete
>>> uuid.uuid4() # doctest: +SKIP
[23] Fix | Delete
UUID('16fd2706-8baf-433b-82eb-8c7fada847da')
[24] Fix | Delete
[25] Fix | Delete
# make a UUID using a SHA-1 hash of a namespace UUID and a name
[26] Fix | Delete
>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
[27] Fix | Delete
UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')
[28] Fix | Delete
[29] Fix | Delete
# make a UUID from a string of hex digits (braces and hyphens ignored)
[30] Fix | Delete
>>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')
[31] Fix | Delete
[32] Fix | Delete
# convert a UUID to a string of hex digits in standard form
[33] Fix | Delete
>>> str(x)
[34] Fix | Delete
'00010203-0405-0607-0809-0a0b0c0d0e0f'
[35] Fix | Delete
[36] Fix | Delete
# get the raw 16 bytes of the UUID
[37] Fix | Delete
>>> x.bytes
[38] Fix | Delete
b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'
[39] Fix | Delete
[40] Fix | Delete
# make a UUID from a 16-byte string
[41] Fix | Delete
>>> uuid.UUID(bytes=x.bytes)
[42] Fix | Delete
UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')
[43] Fix | Delete
"""
[44] Fix | Delete
[45] Fix | Delete
import os
[46] Fix | Delete
import sys
[47] Fix | Delete
[48] Fix | Delete
from enum import Enum
[49] Fix | Delete
[50] Fix | Delete
[51] Fix | Delete
__author__ = 'Ka-Ping Yee <ping@zesty.ca>'
[52] Fix | Delete
[53] Fix | Delete
# The recognized platforms - known behaviors
[54] Fix | Delete
if sys.platform in ('win32', 'darwin'):
[55] Fix | Delete
_AIX = _LINUX = False
[56] Fix | Delete
else:
[57] Fix | Delete
import platform
[58] Fix | Delete
_platform_system = platform.system()
[59] Fix | Delete
_AIX = _platform_system == 'AIX'
[60] Fix | Delete
_LINUX = _platform_system == 'Linux'
[61] Fix | Delete
[62] Fix | Delete
_MAC_DELIM = b':'
[63] Fix | Delete
_MAC_OMITS_LEADING_ZEROES = False
[64] Fix | Delete
if _AIX:
[65] Fix | Delete
_MAC_DELIM = b'.'
[66] Fix | Delete
_MAC_OMITS_LEADING_ZEROES = True
[67] Fix | Delete
[68] Fix | Delete
RESERVED_NCS, RFC_4122, RESERVED_MICROSOFT, RESERVED_FUTURE = [
[69] Fix | Delete
'reserved for NCS compatibility', 'specified in RFC 4122',
[70] Fix | Delete
'reserved for Microsoft compatibility', 'reserved for future definition']
[71] Fix | Delete
[72] Fix | Delete
int_ = int # The built-in int type
[73] Fix | Delete
bytes_ = bytes # The built-in bytes type
[74] Fix | Delete
[75] Fix | Delete
[76] Fix | Delete
class SafeUUID(Enum):
[77] Fix | Delete
safe = 0
[78] Fix | Delete
unsafe = -1
[79] Fix | Delete
unknown = None
[80] Fix | Delete
[81] Fix | Delete
[82] Fix | Delete
class UUID:
[83] Fix | Delete
"""Instances of the UUID class represent UUIDs as specified in RFC 4122.
[84] Fix | Delete
UUID objects are immutable, hashable, and usable as dictionary keys.
[85] Fix | Delete
Converting a UUID to a string with str() yields something in the form
[86] Fix | Delete
'12345678-1234-1234-1234-123456789abc'. The UUID constructor accepts
[87] Fix | Delete
five possible forms: a similar string of hexadecimal digits, or a tuple
[88] Fix | Delete
of six integer fields (with 32-bit, 16-bit, 16-bit, 8-bit, 8-bit, and
[89] Fix | Delete
48-bit values respectively) as an argument named 'fields', or a string
[90] Fix | Delete
of 16 bytes (with all the integer fields in big-endian order) as an
[91] Fix | Delete
argument named 'bytes', or a string of 16 bytes (with the first three
[92] Fix | Delete
fields in little-endian order) as an argument named 'bytes_le', or a
[93] Fix | Delete
single 128-bit integer as an argument named 'int'.
[94] Fix | Delete
[95] Fix | Delete
UUIDs have these read-only attributes:
[96] Fix | Delete
[97] Fix | Delete
bytes the UUID as a 16-byte string (containing the six
[98] Fix | Delete
integer fields in big-endian byte order)
[99] Fix | Delete
[100] Fix | Delete
bytes_le the UUID as a 16-byte string (with time_low, time_mid,
[101] Fix | Delete
and time_hi_version in little-endian byte order)
[102] Fix | Delete
[103] Fix | Delete
fields a tuple of the six integer fields of the UUID,
[104] Fix | Delete
which are also available as six individual attributes
[105] Fix | Delete
and two derived attributes:
[106] Fix | Delete
[107] Fix | Delete
time_low the first 32 bits of the UUID
[108] Fix | Delete
time_mid the next 16 bits of the UUID
[109] Fix | Delete
time_hi_version the next 16 bits of the UUID
[110] Fix | Delete
clock_seq_hi_variant the next 8 bits of the UUID
[111] Fix | Delete
clock_seq_low the next 8 bits of the UUID
[112] Fix | Delete
node the last 48 bits of the UUID
[113] Fix | Delete
[114] Fix | Delete
time the 60-bit timestamp
[115] Fix | Delete
clock_seq the 14-bit sequence number
[116] Fix | Delete
[117] Fix | Delete
hex the UUID as a 32-character hexadecimal string
[118] Fix | Delete
[119] Fix | Delete
int the UUID as a 128-bit integer
[120] Fix | Delete
[121] Fix | Delete
urn the UUID as a URN as specified in RFC 4122
[122] Fix | Delete
[123] Fix | Delete
variant the UUID variant (one of the constants RESERVED_NCS,
[124] Fix | Delete
RFC_4122, RESERVED_MICROSOFT, or RESERVED_FUTURE)
[125] Fix | Delete
[126] Fix | Delete
version the UUID version number (1 through 5, meaningful only
[127] Fix | Delete
when the variant is RFC_4122)
[128] Fix | Delete
[129] Fix | Delete
is_safe An enum indicating whether the UUID has been generated in
[130] Fix | Delete
a way that is safe for multiprocessing applications, via
[131] Fix | Delete
uuid_generate_time_safe(3).
[132] Fix | Delete
"""
[133] Fix | Delete
[134] Fix | Delete
__slots__ = ('int', 'is_safe', '__weakref__')
[135] Fix | Delete
[136] Fix | Delete
def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None,
[137] Fix | Delete
int=None, version=None,
[138] Fix | Delete
*, is_safe=SafeUUID.unknown):
[139] Fix | Delete
r"""Create a UUID from either a string of 32 hexadecimal digits,
[140] Fix | Delete
a string of 16 bytes as the 'bytes' argument, a string of 16 bytes
[141] Fix | Delete
in little-endian order as the 'bytes_le' argument, a tuple of six
[142] Fix | Delete
integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version,
[143] Fix | Delete
8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as
[144] Fix | Delete
the 'fields' argument, or a single 128-bit integer as the 'int'
[145] Fix | Delete
argument. When a string of hex digits is given, curly braces,
[146] Fix | Delete
hyphens, and a URN prefix are all optional. For example, these
[147] Fix | Delete
expressions all yield the same UUID:
[148] Fix | Delete
[149] Fix | Delete
UUID('{12345678-1234-5678-1234-567812345678}')
[150] Fix | Delete
UUID('12345678123456781234567812345678')
[151] Fix | Delete
UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
[152] Fix | Delete
UUID(bytes='\x12\x34\x56\x78'*4)
[153] Fix | Delete
UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' +
[154] Fix | Delete
'\x12\x34\x56\x78\x12\x34\x56\x78')
[155] Fix | Delete
UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
[156] Fix | Delete
UUID(int=0x12345678123456781234567812345678)
[157] Fix | Delete
[158] Fix | Delete
Exactly one of 'hex', 'bytes', 'bytes_le', 'fields', or 'int' must
[159] Fix | Delete
be given. The 'version' argument is optional; if given, the resulting
[160] Fix | Delete
UUID will have its variant and version set according to RFC 4122,
[161] Fix | Delete
overriding the given 'hex', 'bytes', 'bytes_le', 'fields', or 'int'.
[162] Fix | Delete
[163] Fix | Delete
is_safe is an enum exposed as an attribute on the instance. It
[164] Fix | Delete
indicates whether the UUID has been generated in a way that is safe
[165] Fix | Delete
for multiprocessing applications, via uuid_generate_time_safe(3).
[166] Fix | Delete
"""
[167] Fix | Delete
[168] Fix | Delete
if [hex, bytes, bytes_le, fields, int].count(None) != 4:
[169] Fix | Delete
raise TypeError('one of the hex, bytes, bytes_le, fields, '
[170] Fix | Delete
'or int arguments must be given')
[171] Fix | Delete
if hex is not None:
[172] Fix | Delete
hex = hex.replace('urn:', '').replace('uuid:', '')
[173] Fix | Delete
hex = hex.strip('{}').replace('-', '')
[174] Fix | Delete
if len(hex) != 32:
[175] Fix | Delete
raise ValueError('badly formed hexadecimal UUID string')
[176] Fix | Delete
int = int_(hex, 16)
[177] Fix | Delete
if bytes_le is not None:
[178] Fix | Delete
if len(bytes_le) != 16:
[179] Fix | Delete
raise ValueError('bytes_le is not a 16-char string')
[180] Fix | Delete
bytes = (bytes_le[4-1::-1] + bytes_le[6-1:4-1:-1] +
[181] Fix | Delete
bytes_le[8-1:6-1:-1] + bytes_le[8:])
[182] Fix | Delete
if bytes is not None:
[183] Fix | Delete
if len(bytes) != 16:
[184] Fix | Delete
raise ValueError('bytes is not a 16-char string')
[185] Fix | Delete
assert isinstance(bytes, bytes_), repr(bytes)
[186] Fix | Delete
int = int_.from_bytes(bytes, byteorder='big')
[187] Fix | Delete
if fields is not None:
[188] Fix | Delete
if len(fields) != 6:
[189] Fix | Delete
raise ValueError('fields is not a 6-tuple')
[190] Fix | Delete
(time_low, time_mid, time_hi_version,
[191] Fix | Delete
clock_seq_hi_variant, clock_seq_low, node) = fields
[192] Fix | Delete
if not 0 <= time_low < 1<<32:
[193] Fix | Delete
raise ValueError('field 1 out of range (need a 32-bit value)')
[194] Fix | Delete
if not 0 <= time_mid < 1<<16:
[195] Fix | Delete
raise ValueError('field 2 out of range (need a 16-bit value)')
[196] Fix | Delete
if not 0 <= time_hi_version < 1<<16:
[197] Fix | Delete
raise ValueError('field 3 out of range (need a 16-bit value)')
[198] Fix | Delete
if not 0 <= clock_seq_hi_variant < 1<<8:
[199] Fix | Delete
raise ValueError('field 4 out of range (need an 8-bit value)')
[200] Fix | Delete
if not 0 <= clock_seq_low < 1<<8:
[201] Fix | Delete
raise ValueError('field 5 out of range (need an 8-bit value)')
[202] Fix | Delete
if not 0 <= node < 1<<48:
[203] Fix | Delete
raise ValueError('field 6 out of range (need a 48-bit value)')
[204] Fix | Delete
clock_seq = (clock_seq_hi_variant << 8) | clock_seq_low
[205] Fix | Delete
int = ((time_low << 96) | (time_mid << 80) |
[206] Fix | Delete
(time_hi_version << 64) | (clock_seq << 48) | node)
[207] Fix | Delete
if int is not None:
[208] Fix | Delete
if not 0 <= int < 1<<128:
[209] Fix | Delete
raise ValueError('int is out of range (need a 128-bit value)')
[210] Fix | Delete
if version is not None:
[211] Fix | Delete
if not 1 <= version <= 5:
[212] Fix | Delete
raise ValueError('illegal version number')
[213] Fix | Delete
# Set the variant to RFC 4122.
[214] Fix | Delete
int &= ~(0xc000 << 48)
[215] Fix | Delete
int |= 0x8000 << 48
[216] Fix | Delete
# Set the version number.
[217] Fix | Delete
int &= ~(0xf000 << 64)
[218] Fix | Delete
int |= version << 76
[219] Fix | Delete
object.__setattr__(self, 'int', int)
[220] Fix | Delete
object.__setattr__(self, 'is_safe', is_safe)
[221] Fix | Delete
[222] Fix | Delete
def __getstate__(self):
[223] Fix | Delete
d = {'int': self.int}
[224] Fix | Delete
if self.is_safe != SafeUUID.unknown:
[225] Fix | Delete
# is_safe is a SafeUUID instance. Return just its value, so that
[226] Fix | Delete
# it can be un-pickled in older Python versions without SafeUUID.
[227] Fix | Delete
d['is_safe'] = self.is_safe.value
[228] Fix | Delete
return d
[229] Fix | Delete
[230] Fix | Delete
def __setstate__(self, state):
[231] Fix | Delete
object.__setattr__(self, 'int', state['int'])
[232] Fix | Delete
# is_safe was added in 3.7; it is also omitted when it is "unknown"
[233] Fix | Delete
object.__setattr__(self, 'is_safe',
[234] Fix | Delete
SafeUUID(state['is_safe'])
[235] Fix | Delete
if 'is_safe' in state else SafeUUID.unknown)
[236] Fix | Delete
[237] Fix | Delete
def __eq__(self, other):
[238] Fix | Delete
if isinstance(other, UUID):
[239] Fix | Delete
return self.int == other.int
[240] Fix | Delete
return NotImplemented
[241] Fix | Delete
[242] Fix | Delete
# Q. What's the value of being able to sort UUIDs?
[243] Fix | Delete
# A. Use them as keys in a B-Tree or similar mapping.
[244] Fix | Delete
[245] Fix | Delete
def __lt__(self, other):
[246] Fix | Delete
if isinstance(other, UUID):
[247] Fix | Delete
return self.int < other.int
[248] Fix | Delete
return NotImplemented
[249] Fix | Delete
[250] Fix | Delete
def __gt__(self, other):
[251] Fix | Delete
if isinstance(other, UUID):
[252] Fix | Delete
return self.int > other.int
[253] Fix | Delete
return NotImplemented
[254] Fix | Delete
[255] Fix | Delete
def __le__(self, other):
[256] Fix | Delete
if isinstance(other, UUID):
[257] Fix | Delete
return self.int <= other.int
[258] Fix | Delete
return NotImplemented
[259] Fix | Delete
[260] Fix | Delete
def __ge__(self, other):
[261] Fix | Delete
if isinstance(other, UUID):
[262] Fix | Delete
return self.int >= other.int
[263] Fix | Delete
return NotImplemented
[264] Fix | Delete
[265] Fix | Delete
def __hash__(self):
[266] Fix | Delete
return hash(self.int)
[267] Fix | Delete
[268] Fix | Delete
def __int__(self):
[269] Fix | Delete
return self.int
[270] Fix | Delete
[271] Fix | Delete
def __repr__(self):
[272] Fix | Delete
return '%s(%r)' % (self.__class__.__name__, str(self))
[273] Fix | Delete
[274] Fix | Delete
def __setattr__(self, name, value):
[275] Fix | Delete
raise TypeError('UUID objects are immutable')
[276] Fix | Delete
[277] Fix | Delete
def __str__(self):
[278] Fix | Delete
hex = '%032x' % self.int
[279] Fix | Delete
return '%s-%s-%s-%s-%s' % (
[280] Fix | Delete
hex[:8], hex[8:12], hex[12:16], hex[16:20], hex[20:])
[281] Fix | Delete
[282] Fix | Delete
@property
[283] Fix | Delete
def bytes(self):
[284] Fix | Delete
return self.int.to_bytes(16, 'big')
[285] Fix | Delete
[286] Fix | Delete
@property
[287] Fix | Delete
def bytes_le(self):
[288] Fix | Delete
bytes = self.bytes
[289] Fix | Delete
return (bytes[4-1::-1] + bytes[6-1:4-1:-1] + bytes[8-1:6-1:-1] +
[290] Fix | Delete
bytes[8:])
[291] Fix | Delete
[292] Fix | Delete
@property
[293] Fix | Delete
def fields(self):
[294] Fix | Delete
return (self.time_low, self.time_mid, self.time_hi_version,
[295] Fix | Delete
self.clock_seq_hi_variant, self.clock_seq_low, self.node)
[296] Fix | Delete
[297] Fix | Delete
@property
[298] Fix | Delete
def time_low(self):
[299] Fix | Delete
return self.int >> 96
[300] Fix | Delete
[301] Fix | Delete
@property
[302] Fix | Delete
def time_mid(self):
[303] Fix | Delete
return (self.int >> 80) & 0xffff
[304] Fix | Delete
[305] Fix | Delete
@property
[306] Fix | Delete
def time_hi_version(self):
[307] Fix | Delete
return (self.int >> 64) & 0xffff
[308] Fix | Delete
[309] Fix | Delete
@property
[310] Fix | Delete
def clock_seq_hi_variant(self):
[311] Fix | Delete
return (self.int >> 56) & 0xff
[312] Fix | Delete
[313] Fix | Delete
@property
[314] Fix | Delete
def clock_seq_low(self):
[315] Fix | Delete
return (self.int >> 48) & 0xff
[316] Fix | Delete
[317] Fix | Delete
@property
[318] Fix | Delete
def time(self):
[319] Fix | Delete
return (((self.time_hi_version & 0x0fff) << 48) |
[320] Fix | Delete
(self.time_mid << 32) | self.time_low)
[321] Fix | Delete
[322] Fix | Delete
@property
[323] Fix | Delete
def clock_seq(self):
[324] Fix | Delete
return (((self.clock_seq_hi_variant & 0x3f) << 8) |
[325] Fix | Delete
self.clock_seq_low)
[326] Fix | Delete
[327] Fix | Delete
@property
[328] Fix | Delete
def node(self):
[329] Fix | Delete
return self.int & 0xffffffffffff
[330] Fix | Delete
[331] Fix | Delete
@property
[332] Fix | Delete
def hex(self):
[333] Fix | Delete
return '%032x' % self.int
[334] Fix | Delete
[335] Fix | Delete
@property
[336] Fix | Delete
def urn(self):
[337] Fix | Delete
return 'urn:uuid:' + str(self)
[338] Fix | Delete
[339] Fix | Delete
@property
[340] Fix | Delete
def variant(self):
[341] Fix | Delete
if not self.int & (0x8000 << 48):
[342] Fix | Delete
return RESERVED_NCS
[343] Fix | Delete
elif not self.int & (0x4000 << 48):
[344] Fix | Delete
return RFC_4122
[345] Fix | Delete
elif not self.int & (0x2000 << 48):
[346] Fix | Delete
return RESERVED_MICROSOFT
[347] Fix | Delete
else:
[348] Fix | Delete
return RESERVED_FUTURE
[349] Fix | Delete
[350] Fix | Delete
@property
[351] Fix | Delete
def version(self):
[352] Fix | Delete
# The version bits are only meaningful for RFC 4122 UUIDs.
[353] Fix | Delete
if self.variant == RFC_4122:
[354] Fix | Delete
return int((self.int >> 76) & 0xf)
[355] Fix | Delete
[356] Fix | Delete
[357] Fix | Delete
def _get_command_stdout(command, *args):
[358] Fix | Delete
import io, os, shutil, subprocess
[359] Fix | Delete
[360] Fix | Delete
try:
[361] Fix | Delete
path_dirs = os.environ.get('PATH', os.defpath).split(os.pathsep)
[362] Fix | Delete
path_dirs.extend(['/sbin', '/usr/sbin'])
[363] Fix | Delete
executable = shutil.which(command, path=os.pathsep.join(path_dirs))
[364] Fix | Delete
if executable is None:
[365] Fix | Delete
return None
[366] Fix | Delete
# LC_ALL=C to ensure English output, stderr=DEVNULL to prevent output
[367] Fix | Delete
# on stderr (Note: we don't have an example where the words we search
[368] Fix | Delete
# for are actually localized, but in theory some system could do so.)
[369] Fix | Delete
env = dict(os.environ)
[370] Fix | Delete
env['LC_ALL'] = 'C'
[371] Fix | Delete
proc = subprocess.Popen((executable,) + args,
[372] Fix | Delete
stdout=subprocess.PIPE,
[373] Fix | Delete
stderr=subprocess.DEVNULL,
[374] Fix | Delete
env=env)
[375] Fix | Delete
if not proc:
[376] Fix | Delete
return None
[377] Fix | Delete
stdout, stderr = proc.communicate()
[378] Fix | Delete
return io.BytesIO(stdout)
[379] Fix | Delete
except (OSError, subprocess.SubprocessError):
[380] Fix | Delete
return None
[381] Fix | Delete
[382] Fix | Delete
[383] Fix | Delete
# For MAC (a.k.a. IEEE 802, or EUI-48) addresses, the second least significant
[384] Fix | Delete
# bit of the first octet signifies whether the MAC address is universally (0)
[385] Fix | Delete
# or locally (1) administered. Network cards from hardware manufacturers will
[386] Fix | Delete
# always be universally administered to guarantee global uniqueness of the MAC
[387] Fix | Delete
# address, but any particular machine may have other interfaces which are
[388] Fix | Delete
# locally administered. An example of the latter is the bridge interface to
[389] Fix | Delete
# the Touch Bar on MacBook Pros.
[390] Fix | Delete
#
[391] Fix | Delete
# This bit works out to be the 42nd bit counting from 1 being the least
[392] Fix | Delete
# significant, or 1<<41. We'll prefer universally administered MAC addresses
[393] Fix | Delete
# over locally administered ones since the former are globally unique, but
[394] Fix | Delete
# we'll return the first of the latter found if that's all the machine has.
[395] Fix | Delete
#
[396] Fix | Delete
# See https://en.wikipedia.org/wiki/MAC_address#Universal_vs._local
[397] Fix | Delete
[398] Fix | Delete
def _is_universal(mac):
[399] Fix | Delete
return not (mac & (1 << 41))
[400] Fix | Delete
[401] Fix | Delete
[402] Fix | Delete
def _find_mac_near_keyword(command, args, keywords, get_word_index):
[403] Fix | Delete
"""Searches a command's output for a MAC address near a keyword.
[404] Fix | Delete
[405] Fix | Delete
Each line of words in the output is case-insensitively searched for
[406] Fix | Delete
any of the given keywords. Upon a match, get_word_index is invoked
[407] Fix | Delete
to pick a word from the line, given the index of the match. For
[408] Fix | Delete
example, lambda i: 0 would get the first word on the line, while
[409] Fix | Delete
lambda i: i - 1 would get the word preceding the keyword.
[410] Fix | Delete
"""
[411] Fix | Delete
stdout = _get_command_stdout(command, args)
[412] Fix | Delete
if stdout is None:
[413] Fix | Delete
return None
[414] Fix | Delete
[415] Fix | Delete
first_local_mac = None
[416] Fix | Delete
for line in stdout:
[417] Fix | Delete
words = line.lower().rstrip().split()
[418] Fix | Delete
for i in range(len(words)):
[419] Fix | Delete
if words[i] in keywords:
[420] Fix | Delete
try:
[421] Fix | Delete
word = words[get_word_index(i)]
[422] Fix | Delete
mac = int(word.replace(_MAC_DELIM, b''), 16)
[423] Fix | Delete
except (ValueError, IndexError):
[424] Fix | Delete
# Virtual interfaces, such as those provided by
[425] Fix | Delete
# VPNs, do not have a colon-delimited MAC address
[426] Fix | Delete
# as expected, but a 16-byte HWAddr separated by
[427] Fix | Delete
# dashes. These should be ignored in favor of a
[428] Fix | Delete
# real MAC address
[429] Fix | Delete
pass
[430] Fix | Delete
else:
[431] Fix | Delete
if _is_universal(mac):
[432] Fix | Delete
return mac
[433] Fix | Delete
first_local_mac = first_local_mac or mac
[434] Fix | Delete
return first_local_mac or None
[435] Fix | Delete
[436] Fix | Delete
[437] Fix | Delete
def _parse_mac(word):
[438] Fix | Delete
# Accept 'HH:HH:HH:HH:HH:HH' MAC address (ex: '52:54:00:9d:0e:67'),
[439] Fix | Delete
# but reject IPv6 address (ex: 'fe80::5054:ff:fe9' or '123:2:3:4:5:6:7:8').
[440] Fix | Delete
#
[441] Fix | Delete
# Virtual interfaces, such as those provided by VPNs, do not have a
[442] Fix | Delete
# colon-delimited MAC address as expected, but a 16-byte HWAddr separated
[443] Fix | Delete
# by dashes. These should be ignored in favor of a real MAC address
[444] Fix | Delete
parts = word.split(_MAC_DELIM)
[445] Fix | Delete
if len(parts) != 6:
[446] Fix | Delete
return
[447] Fix | Delete
if _MAC_OMITS_LEADING_ZEROES:
[448] Fix | Delete
# (Only) on AIX the macaddr value given is not prefixed by 0, e.g.
[449] Fix | Delete
# en0 1500 link#2 fa.bc.de.f7.62.4 110854824 0 160133733 0 0
[450] Fix | Delete
# not
[451] Fix | Delete
# en0 1500 link#2 fa.bc.de.f7.62.04 110854824 0 160133733 0 0
[452] Fix | Delete
if not all(1 <= len(part) <= 2 for part in parts):
[453] Fix | Delete
return
[454] Fix | Delete
hexstr = b''.join(part.rjust(2, b'0') for part in parts)
[455] Fix | Delete
else:
[456] Fix | Delete
if not all(len(part) == 2 for part in parts):
[457] Fix | Delete
return
[458] Fix | Delete
hexstr = b''.join(parts)
[459] Fix | Delete
try:
[460] Fix | Delete
return int(hexstr, 16)
[461] Fix | Delete
except ValueError:
[462] Fix | Delete
return
[463] Fix | Delete
[464] Fix | Delete
[465] Fix | Delete
def _find_mac_under_heading(command, args, heading):
[466] Fix | Delete
"""Looks for a MAC address under a heading in a command's output.
[467] Fix | Delete
[468] Fix | Delete
The first line of words in the output is searched for the given
[469] Fix | Delete
heading. Words at the same word index as the heading in subsequent
[470] Fix | Delete
lines are then examined to see if they look like MAC addresses.
[471] Fix | Delete
"""
[472] Fix | Delete
stdout = _get_command_stdout(command, args)
[473] Fix | Delete
if stdout is None:
[474] Fix | Delete
return None
[475] Fix | Delete
[476] Fix | Delete
keywords = stdout.readline().rstrip().split()
[477] Fix | Delete
try:
[478] Fix | Delete
column_index = keywords.index(heading)
[479] Fix | Delete
except ValueError:
[480] Fix | Delete
return None
[481] Fix | Delete
[482] Fix | Delete
first_local_mac = None
[483] Fix | Delete
for line in stdout:
[484] Fix | Delete
words = line.rstrip().split()
[485] Fix | Delete
try:
[486] Fix | Delete
word = words[column_index]
[487] Fix | Delete
except IndexError:
[488] Fix | Delete
continue
[489] Fix | Delete
[490] Fix | Delete
mac = _parse_mac(word)
[491] Fix | Delete
if mac is None:
[492] Fix | Delete
continue
[493] Fix | Delete
if _is_universal(mac):
[494] Fix | Delete
return mac
[495] Fix | Delete
if first_local_mac is None:
[496] Fix | Delete
first_local_mac = mac
[497] Fix | Delete
[498] Fix | Delete
return first_local_mac
[499] Fix | Delete
12
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function