| 1 | n/a | r"""UUID objects (universally unique identifiers) according to RFC 4122. |
|---|
| 2 | n/a | |
|---|
| 3 | n/a | This module provides immutable UUID objects (class UUID) and the functions |
|---|
| 4 | n/a | uuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5 |
|---|
| 5 | n/a | UUIDs as specified in RFC 4122. |
|---|
| 6 | n/a | |
|---|
| 7 | n/a | If all you want is a unique ID, you should probably call uuid1() or uuid4(). |
|---|
| 8 | n/a | Note that uuid1() may compromise privacy since it creates a UUID containing |
|---|
| 9 | n/a | the computer's network address. uuid4() creates a random UUID. |
|---|
| 10 | n/a | |
|---|
| 11 | n/a | Typical usage: |
|---|
| 12 | n/a | |
|---|
| 13 | n/a | >>> import uuid |
|---|
| 14 | n/a | |
|---|
| 15 | n/a | # make a UUID based on the host ID and current time |
|---|
| 16 | n/a | >>> uuid.uuid1() # doctest: +SKIP |
|---|
| 17 | n/a | UUID('a8098c1a-f86e-11da-bd1a-00112444be1e') |
|---|
| 18 | n/a | |
|---|
| 19 | n/a | # make a UUID using an MD5 hash of a namespace UUID and a name |
|---|
| 20 | n/a | >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org') |
|---|
| 21 | n/a | UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e') |
|---|
| 22 | n/a | |
|---|
| 23 | n/a | # make a random UUID |
|---|
| 24 | n/a | >>> uuid.uuid4() # doctest: +SKIP |
|---|
| 25 | n/a | UUID('16fd2706-8baf-433b-82eb-8c7fada847da') |
|---|
| 26 | n/a | |
|---|
| 27 | n/a | # make a UUID using a SHA-1 hash of a namespace UUID and a name |
|---|
| 28 | n/a | >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org') |
|---|
| 29 | n/a | UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d') |
|---|
| 30 | n/a | |
|---|
| 31 | n/a | # make a UUID from a string of hex digits (braces and hyphens ignored) |
|---|
| 32 | n/a | >>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}') |
|---|
| 33 | n/a | |
|---|
| 34 | n/a | # convert a UUID to a string of hex digits in standard form |
|---|
| 35 | n/a | >>> str(x) |
|---|
| 36 | n/a | '00010203-0405-0607-0809-0a0b0c0d0e0f' |
|---|
| 37 | n/a | |
|---|
| 38 | n/a | # get the raw 16 bytes of the UUID |
|---|
| 39 | n/a | >>> x.bytes |
|---|
| 40 | n/a | b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f' |
|---|
| 41 | n/a | |
|---|
| 42 | n/a | # make a UUID from a 16-byte string |
|---|
| 43 | n/a | >>> uuid.UUID(bytes=x.bytes) |
|---|
| 44 | n/a | UUID('00010203-0405-0607-0809-0a0b0c0d0e0f') |
|---|
| 45 | n/a | """ |
|---|
| 46 | n/a | |
|---|
| 47 | n/a | import os |
|---|
| 48 | n/a | |
|---|
| 49 | n/a | __author__ = 'Ka-Ping Yee <ping@zesty.ca>' |
|---|
| 50 | n/a | |
|---|
| 51 | n/a | RESERVED_NCS, RFC_4122, RESERVED_MICROSOFT, RESERVED_FUTURE = [ |
|---|
| 52 | n/a | 'reserved for NCS compatibility', 'specified in RFC 4122', |
|---|
| 53 | n/a | 'reserved for Microsoft compatibility', 'reserved for future definition'] |
|---|
| 54 | n/a | |
|---|
| 55 | n/a | int_ = int # The built-in int type |
|---|
| 56 | n/a | bytes_ = bytes # The built-in bytes type |
|---|
| 57 | n/a | |
|---|
| 58 | n/a | class UUID(object): |
|---|
| 59 | n/a | """Instances of the UUID class represent UUIDs as specified in RFC 4122. |
|---|
| 60 | n/a | UUID objects are immutable, hashable, and usable as dictionary keys. |
|---|
| 61 | n/a | Converting a UUID to a string with str() yields something in the form |
|---|
| 62 | n/a | '12345678-1234-1234-1234-123456789abc'. The UUID constructor accepts |
|---|
| 63 | n/a | five possible forms: a similar string of hexadecimal digits, or a tuple |
|---|
| 64 | n/a | of six integer fields (with 32-bit, 16-bit, 16-bit, 8-bit, 8-bit, and |
|---|
| 65 | n/a | 48-bit values respectively) as an argument named 'fields', or a string |
|---|
| 66 | n/a | of 16 bytes (with all the integer fields in big-endian order) as an |
|---|
| 67 | n/a | argument named 'bytes', or a string of 16 bytes (with the first three |
|---|
| 68 | n/a | fields in little-endian order) as an argument named 'bytes_le', or a |
|---|
| 69 | n/a | single 128-bit integer as an argument named 'int'. |
|---|
| 70 | n/a | |
|---|
| 71 | n/a | UUIDs have these read-only attributes: |
|---|
| 72 | n/a | |
|---|
| 73 | n/a | bytes the UUID as a 16-byte string (containing the six |
|---|
| 74 | n/a | integer fields in big-endian byte order) |
|---|
| 75 | n/a | |
|---|
| 76 | n/a | bytes_le the UUID as a 16-byte string (with time_low, time_mid, |
|---|
| 77 | n/a | and time_hi_version in little-endian byte order) |
|---|
| 78 | n/a | |
|---|
| 79 | n/a | fields a tuple of the six integer fields of the UUID, |
|---|
| 80 | n/a | which are also available as six individual attributes |
|---|
| 81 | n/a | and two derived attributes: |
|---|
| 82 | n/a | |
|---|
| 83 | n/a | time_low the first 32 bits of the UUID |
|---|
| 84 | n/a | time_mid the next 16 bits of the UUID |
|---|
| 85 | n/a | time_hi_version the next 16 bits of the UUID |
|---|
| 86 | n/a | clock_seq_hi_variant the next 8 bits of the UUID |
|---|
| 87 | n/a | clock_seq_low the next 8 bits of the UUID |
|---|
| 88 | n/a | node the last 48 bits of the UUID |
|---|
| 89 | n/a | |
|---|
| 90 | n/a | time the 60-bit timestamp |
|---|
| 91 | n/a | clock_seq the 14-bit sequence number |
|---|
| 92 | n/a | |
|---|
| 93 | n/a | hex the UUID as a 32-character hexadecimal string |
|---|
| 94 | n/a | |
|---|
| 95 | n/a | int the UUID as a 128-bit integer |
|---|
| 96 | n/a | |
|---|
| 97 | n/a | urn the UUID as a URN as specified in RFC 4122 |
|---|
| 98 | n/a | |
|---|
| 99 | n/a | variant the UUID variant (one of the constants RESERVED_NCS, |
|---|
| 100 | n/a | RFC_4122, RESERVED_MICROSOFT, or RESERVED_FUTURE) |
|---|
| 101 | n/a | |
|---|
| 102 | n/a | version the UUID version number (1 through 5, meaningful only |
|---|
| 103 | n/a | when the variant is RFC_4122) |
|---|
| 104 | n/a | """ |
|---|
| 105 | n/a | |
|---|
| 106 | n/a | def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None, |
|---|
| 107 | n/a | int=None, version=None): |
|---|
| 108 | n/a | r"""Create a UUID from either a string of 32 hexadecimal digits, |
|---|
| 109 | n/a | a string of 16 bytes as the 'bytes' argument, a string of 16 bytes |
|---|
| 110 | n/a | in little-endian order as the 'bytes_le' argument, a tuple of six |
|---|
| 111 | n/a | integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version, |
|---|
| 112 | n/a | 8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as |
|---|
| 113 | n/a | the 'fields' argument, or a single 128-bit integer as the 'int' |
|---|
| 114 | n/a | argument. When a string of hex digits is given, curly braces, |
|---|
| 115 | n/a | hyphens, and a URN prefix are all optional. For example, these |
|---|
| 116 | n/a | expressions all yield the same UUID: |
|---|
| 117 | n/a | |
|---|
| 118 | n/a | UUID('{12345678-1234-5678-1234-567812345678}') |
|---|
| 119 | n/a | UUID('12345678123456781234567812345678') |
|---|
| 120 | n/a | UUID('urn:uuid:12345678-1234-5678-1234-567812345678') |
|---|
| 121 | n/a | UUID(bytes='\x12\x34\x56\x78'*4) |
|---|
| 122 | n/a | UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' + |
|---|
| 123 | n/a | '\x12\x34\x56\x78\x12\x34\x56\x78') |
|---|
| 124 | n/a | UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678)) |
|---|
| 125 | n/a | UUID(int=0x12345678123456781234567812345678) |
|---|
| 126 | n/a | |
|---|
| 127 | n/a | Exactly one of 'hex', 'bytes', 'bytes_le', 'fields', or 'int' must |
|---|
| 128 | n/a | be given. The 'version' argument is optional; if given, the resulting |
|---|
| 129 | n/a | UUID will have its variant and version set according to RFC 4122, |
|---|
| 130 | n/a | overriding the given 'hex', 'bytes', 'bytes_le', 'fields', or 'int'. |
|---|
| 131 | n/a | """ |
|---|
| 132 | n/a | |
|---|
| 133 | n/a | if [hex, bytes, bytes_le, fields, int].count(None) != 4: |
|---|
| 134 | n/a | raise TypeError('one of the hex, bytes, bytes_le, fields, ' |
|---|
| 135 | n/a | 'or int arguments must be given') |
|---|
| 136 | n/a | if hex is not None: |
|---|
| 137 | n/a | hex = hex.replace('urn:', '').replace('uuid:', '') |
|---|
| 138 | n/a | hex = hex.strip('{}').replace('-', '') |
|---|
| 139 | n/a | if len(hex) != 32: |
|---|
| 140 | n/a | raise ValueError('badly formed hexadecimal UUID string') |
|---|
| 141 | n/a | int = int_(hex, 16) |
|---|
| 142 | n/a | if bytes_le is not None: |
|---|
| 143 | n/a | if len(bytes_le) != 16: |
|---|
| 144 | n/a | raise ValueError('bytes_le is not a 16-char string') |
|---|
| 145 | n/a | bytes = (bytes_le[4-1::-1] + bytes_le[6-1:4-1:-1] + |
|---|
| 146 | n/a | bytes_le[8-1:6-1:-1] + bytes_le[8:]) |
|---|
| 147 | n/a | if bytes is not None: |
|---|
| 148 | n/a | if len(bytes) != 16: |
|---|
| 149 | n/a | raise ValueError('bytes is not a 16-char string') |
|---|
| 150 | n/a | assert isinstance(bytes, bytes_), repr(bytes) |
|---|
| 151 | n/a | int = int_.from_bytes(bytes, byteorder='big') |
|---|
| 152 | n/a | if fields is not None: |
|---|
| 153 | n/a | if len(fields) != 6: |
|---|
| 154 | n/a | raise ValueError('fields is not a 6-tuple') |
|---|
| 155 | n/a | (time_low, time_mid, time_hi_version, |
|---|
| 156 | n/a | clock_seq_hi_variant, clock_seq_low, node) = fields |
|---|
| 157 | n/a | if not 0 <= time_low < 1<<32: |
|---|
| 158 | n/a | raise ValueError('field 1 out of range (need a 32-bit value)') |
|---|
| 159 | n/a | if not 0 <= time_mid < 1<<16: |
|---|
| 160 | n/a | raise ValueError('field 2 out of range (need a 16-bit value)') |
|---|
| 161 | n/a | if not 0 <= time_hi_version < 1<<16: |
|---|
| 162 | n/a | raise ValueError('field 3 out of range (need a 16-bit value)') |
|---|
| 163 | n/a | if not 0 <= clock_seq_hi_variant < 1<<8: |
|---|
| 164 | n/a | raise ValueError('field 4 out of range (need an 8-bit value)') |
|---|
| 165 | n/a | if not 0 <= clock_seq_low < 1<<8: |
|---|
| 166 | n/a | raise ValueError('field 5 out of range (need an 8-bit value)') |
|---|
| 167 | n/a | if not 0 <= node < 1<<48: |
|---|
| 168 | n/a | raise ValueError('field 6 out of range (need a 48-bit value)') |
|---|
| 169 | n/a | clock_seq = (clock_seq_hi_variant << 8) | clock_seq_low |
|---|
| 170 | n/a | int = ((time_low << 96) | (time_mid << 80) | |
|---|
| 171 | n/a | (time_hi_version << 64) | (clock_seq << 48) | node) |
|---|
| 172 | n/a | if int is not None: |
|---|
| 173 | n/a | if not 0 <= int < 1<<128: |
|---|
| 174 | n/a | raise ValueError('int is out of range (need a 128-bit value)') |
|---|
| 175 | n/a | if version is not None: |
|---|
| 176 | n/a | if not 1 <= version <= 5: |
|---|
| 177 | n/a | raise ValueError('illegal version number') |
|---|
| 178 | n/a | # Set the variant to RFC 4122. |
|---|
| 179 | n/a | int &= ~(0xc000 << 48) |
|---|
| 180 | n/a | int |= 0x8000 << 48 |
|---|
| 181 | n/a | # Set the version number. |
|---|
| 182 | n/a | int &= ~(0xf000 << 64) |
|---|
| 183 | n/a | int |= version << 76 |
|---|
| 184 | n/a | self.__dict__['int'] = int |
|---|
| 185 | n/a | |
|---|
| 186 | n/a | def __eq__(self, other): |
|---|
| 187 | n/a | if isinstance(other, UUID): |
|---|
| 188 | n/a | return self.int == other.int |
|---|
| 189 | n/a | return NotImplemented |
|---|
| 190 | n/a | |
|---|
| 191 | n/a | # Q. What's the value of being able to sort UUIDs? |
|---|
| 192 | n/a | # A. Use them as keys in a B-Tree or similar mapping. |
|---|
| 193 | n/a | |
|---|
| 194 | n/a | def __lt__(self, other): |
|---|
| 195 | n/a | if isinstance(other, UUID): |
|---|
| 196 | n/a | return self.int < other.int |
|---|
| 197 | n/a | return NotImplemented |
|---|
| 198 | n/a | |
|---|
| 199 | n/a | def __gt__(self, other): |
|---|
| 200 | n/a | if isinstance(other, UUID): |
|---|
| 201 | n/a | return self.int > other.int |
|---|
| 202 | n/a | return NotImplemented |
|---|
| 203 | n/a | |
|---|
| 204 | n/a | def __le__(self, other): |
|---|
| 205 | n/a | if isinstance(other, UUID): |
|---|
| 206 | n/a | return self.int <= other.int |
|---|
| 207 | n/a | return NotImplemented |
|---|
| 208 | n/a | |
|---|
| 209 | n/a | def __ge__(self, other): |
|---|
| 210 | n/a | if isinstance(other, UUID): |
|---|
| 211 | n/a | return self.int >= other.int |
|---|
| 212 | n/a | return NotImplemented |
|---|
| 213 | n/a | |
|---|
| 214 | n/a | def __hash__(self): |
|---|
| 215 | n/a | return hash(self.int) |
|---|
| 216 | n/a | |
|---|
| 217 | n/a | def __int__(self): |
|---|
| 218 | n/a | return self.int |
|---|
| 219 | n/a | |
|---|
| 220 | n/a | def __repr__(self): |
|---|
| 221 | n/a | return '%s(%r)' % (self.__class__.__name__, str(self)) |
|---|
| 222 | n/a | |
|---|
| 223 | n/a | def __setattr__(self, name, value): |
|---|
| 224 | n/a | raise TypeError('UUID objects are immutable') |
|---|
| 225 | n/a | |
|---|
| 226 | n/a | def __str__(self): |
|---|
| 227 | n/a | hex = '%032x' % self.int |
|---|
| 228 | n/a | return '%s-%s-%s-%s-%s' % ( |
|---|
| 229 | n/a | hex[:8], hex[8:12], hex[12:16], hex[16:20], hex[20:]) |
|---|
| 230 | n/a | |
|---|
| 231 | n/a | @property |
|---|
| 232 | n/a | def bytes(self): |
|---|
| 233 | n/a | return self.int.to_bytes(16, 'big') |
|---|
| 234 | n/a | |
|---|
| 235 | n/a | @property |
|---|
| 236 | n/a | def bytes_le(self): |
|---|
| 237 | n/a | bytes = self.bytes |
|---|
| 238 | n/a | return (bytes[4-1::-1] + bytes[6-1:4-1:-1] + bytes[8-1:6-1:-1] + |
|---|
| 239 | n/a | bytes[8:]) |
|---|
| 240 | n/a | |
|---|
| 241 | n/a | @property |
|---|
| 242 | n/a | def fields(self): |
|---|
| 243 | n/a | return (self.time_low, self.time_mid, self.time_hi_version, |
|---|
| 244 | n/a | self.clock_seq_hi_variant, self.clock_seq_low, self.node) |
|---|
| 245 | n/a | |
|---|
| 246 | n/a | @property |
|---|
| 247 | n/a | def time_low(self): |
|---|
| 248 | n/a | return self.int >> 96 |
|---|
| 249 | n/a | |
|---|
| 250 | n/a | @property |
|---|
| 251 | n/a | def time_mid(self): |
|---|
| 252 | n/a | return (self.int >> 80) & 0xffff |
|---|
| 253 | n/a | |
|---|
| 254 | n/a | @property |
|---|
| 255 | n/a | def time_hi_version(self): |
|---|
| 256 | n/a | return (self.int >> 64) & 0xffff |
|---|
| 257 | n/a | |
|---|
| 258 | n/a | @property |
|---|
| 259 | n/a | def clock_seq_hi_variant(self): |
|---|
| 260 | n/a | return (self.int >> 56) & 0xff |
|---|
| 261 | n/a | |
|---|
| 262 | n/a | @property |
|---|
| 263 | n/a | def clock_seq_low(self): |
|---|
| 264 | n/a | return (self.int >> 48) & 0xff |
|---|
| 265 | n/a | |
|---|
| 266 | n/a | @property |
|---|
| 267 | n/a | def time(self): |
|---|
| 268 | n/a | return (((self.time_hi_version & 0x0fff) << 48) | |
|---|
| 269 | n/a | (self.time_mid << 32) | self.time_low) |
|---|
| 270 | n/a | |
|---|
| 271 | n/a | @property |
|---|
| 272 | n/a | def clock_seq(self): |
|---|
| 273 | n/a | return (((self.clock_seq_hi_variant & 0x3f) << 8) | |
|---|
| 274 | n/a | self.clock_seq_low) |
|---|
| 275 | n/a | |
|---|
| 276 | n/a | @property |
|---|
| 277 | n/a | def node(self): |
|---|
| 278 | n/a | return self.int & 0xffffffffffff |
|---|
| 279 | n/a | |
|---|
| 280 | n/a | @property |
|---|
| 281 | n/a | def hex(self): |
|---|
| 282 | n/a | return '%032x' % self.int |
|---|
| 283 | n/a | |
|---|
| 284 | n/a | @property |
|---|
| 285 | n/a | def urn(self): |
|---|
| 286 | n/a | return 'urn:uuid:' + str(self) |
|---|
| 287 | n/a | |
|---|
| 288 | n/a | @property |
|---|
| 289 | n/a | def variant(self): |
|---|
| 290 | n/a | if not self.int & (0x8000 << 48): |
|---|
| 291 | n/a | return RESERVED_NCS |
|---|
| 292 | n/a | elif not self.int & (0x4000 << 48): |
|---|
| 293 | n/a | return RFC_4122 |
|---|
| 294 | n/a | elif not self.int & (0x2000 << 48): |
|---|
| 295 | n/a | return RESERVED_MICROSOFT |
|---|
| 296 | n/a | else: |
|---|
| 297 | n/a | return RESERVED_FUTURE |
|---|
| 298 | n/a | |
|---|
| 299 | n/a | @property |
|---|
| 300 | n/a | def version(self): |
|---|
| 301 | n/a | # The version bits are only meaningful for RFC 4122 UUIDs. |
|---|
| 302 | n/a | if self.variant == RFC_4122: |
|---|
| 303 | n/a | return int((self.int >> 76) & 0xf) |
|---|
| 304 | n/a | |
|---|
| 305 | n/a | def _popen(command, *args): |
|---|
| 306 | n/a | import os, shutil, subprocess |
|---|
| 307 | n/a | executable = shutil.which(command) |
|---|
| 308 | n/a | if executable is None: |
|---|
| 309 | n/a | path = os.pathsep.join(('/sbin', '/usr/sbin')) |
|---|
| 310 | n/a | executable = shutil.which(command, path=path) |
|---|
| 311 | n/a | if executable is None: |
|---|
| 312 | n/a | return None |
|---|
| 313 | n/a | # LC_ALL=C to ensure English output, stderr=DEVNULL to prevent output |
|---|
| 314 | n/a | # on stderr (Note: we don't have an example where the words we search |
|---|
| 315 | n/a | # for are actually localized, but in theory some system could do so.) |
|---|
| 316 | n/a | env = dict(os.environ) |
|---|
| 317 | n/a | env['LC_ALL'] = 'C' |
|---|
| 318 | n/a | proc = subprocess.Popen((executable,) + args, |
|---|
| 319 | n/a | stdout=subprocess.PIPE, |
|---|
| 320 | n/a | stderr=subprocess.DEVNULL, |
|---|
| 321 | n/a | env=env) |
|---|
| 322 | n/a | return proc |
|---|
| 323 | n/a | |
|---|
| 324 | n/a | def _find_mac(command, args, hw_identifiers, get_index): |
|---|
| 325 | n/a | try: |
|---|
| 326 | n/a | proc = _popen(command, *args.split()) |
|---|
| 327 | n/a | if not proc: |
|---|
| 328 | n/a | return |
|---|
| 329 | n/a | with proc: |
|---|
| 330 | n/a | for line in proc.stdout: |
|---|
| 331 | n/a | words = line.lower().rstrip().split() |
|---|
| 332 | n/a | for i in range(len(words)): |
|---|
| 333 | n/a | if words[i] in hw_identifiers: |
|---|
| 334 | n/a | try: |
|---|
| 335 | n/a | word = words[get_index(i)] |
|---|
| 336 | n/a | mac = int(word.replace(b':', b''), 16) |
|---|
| 337 | n/a | if mac: |
|---|
| 338 | n/a | return mac |
|---|
| 339 | n/a | except (ValueError, IndexError): |
|---|
| 340 | n/a | # Virtual interfaces, such as those provided by |
|---|
| 341 | n/a | # VPNs, do not have a colon-delimited MAC address |
|---|
| 342 | n/a | # as expected, but a 16-byte HWAddr separated by |
|---|
| 343 | n/a | # dashes. These should be ignored in favor of a |
|---|
| 344 | n/a | # real MAC address |
|---|
| 345 | n/a | pass |
|---|
| 346 | n/a | except OSError: |
|---|
| 347 | n/a | pass |
|---|
| 348 | n/a | |
|---|
| 349 | n/a | def _ifconfig_getnode(): |
|---|
| 350 | n/a | """Get the hardware address on Unix by running ifconfig.""" |
|---|
| 351 | n/a | # This works on Linux ('' or '-a'), Tru64 ('-av'), but not all Unixes. |
|---|
| 352 | n/a | for args in ('', '-a', '-av'): |
|---|
| 353 | n/a | mac = _find_mac('ifconfig', args, [b'hwaddr', b'ether'], lambda i: i+1) |
|---|
| 354 | n/a | if mac: |
|---|
| 355 | n/a | return mac |
|---|
| 356 | n/a | |
|---|
| 357 | n/a | def _ip_getnode(): |
|---|
| 358 | n/a | """Get the hardware address on Unix by running ip.""" |
|---|
| 359 | n/a | # This works on Linux with iproute2. |
|---|
| 360 | n/a | mac = _find_mac('ip', 'link list', [b'link/ether'], lambda i: i+1) |
|---|
| 361 | n/a | if mac: |
|---|
| 362 | n/a | return mac |
|---|
| 363 | n/a | |
|---|
| 364 | n/a | def _arp_getnode(): |
|---|
| 365 | n/a | """Get the hardware address on Unix by running arp.""" |
|---|
| 366 | n/a | import os, socket |
|---|
| 367 | n/a | try: |
|---|
| 368 | n/a | ip_addr = socket.gethostbyname(socket.gethostname()) |
|---|
| 369 | n/a | except OSError: |
|---|
| 370 | n/a | return None |
|---|
| 371 | n/a | |
|---|
| 372 | n/a | # Try getting the MAC addr from arp based on our IP address (Solaris). |
|---|
| 373 | n/a | return _find_mac('arp', '-an', [os.fsencode(ip_addr)], lambda i: -1) |
|---|
| 374 | n/a | |
|---|
| 375 | n/a | def _lanscan_getnode(): |
|---|
| 376 | n/a | """Get the hardware address on Unix by running lanscan.""" |
|---|
| 377 | n/a | # This might work on HP-UX. |
|---|
| 378 | n/a | return _find_mac('lanscan', '-ai', [b'lan0'], lambda i: 0) |
|---|
| 379 | n/a | |
|---|
| 380 | n/a | def _netstat_getnode(): |
|---|
| 381 | n/a | """Get the hardware address on Unix by running netstat.""" |
|---|
| 382 | n/a | # This might work on AIX, Tru64 UNIX and presumably on IRIX. |
|---|
| 383 | n/a | try: |
|---|
| 384 | n/a | proc = _popen('netstat', '-ia') |
|---|
| 385 | n/a | if not proc: |
|---|
| 386 | n/a | return |
|---|
| 387 | n/a | with proc: |
|---|
| 388 | n/a | words = proc.stdout.readline().rstrip().split() |
|---|
| 389 | n/a | try: |
|---|
| 390 | n/a | i = words.index(b'Address') |
|---|
| 391 | n/a | except ValueError: |
|---|
| 392 | n/a | return |
|---|
| 393 | n/a | for line in proc.stdout: |
|---|
| 394 | n/a | try: |
|---|
| 395 | n/a | words = line.rstrip().split() |
|---|
| 396 | n/a | word = words[i] |
|---|
| 397 | n/a | if len(word) == 17 and word.count(b':') == 5: |
|---|
| 398 | n/a | mac = int(word.replace(b':', b''), 16) |
|---|
| 399 | n/a | if mac: |
|---|
| 400 | n/a | return mac |
|---|
| 401 | n/a | except (ValueError, IndexError): |
|---|
| 402 | n/a | pass |
|---|
| 403 | n/a | except OSError: |
|---|
| 404 | n/a | pass |
|---|
| 405 | n/a | |
|---|
| 406 | n/a | def _ipconfig_getnode(): |
|---|
| 407 | n/a | """Get the hardware address on Windows by running ipconfig.exe.""" |
|---|
| 408 | n/a | import os, re |
|---|
| 409 | n/a | dirs = ['', r'c:\windows\system32', r'c:\winnt\system32'] |
|---|
| 410 | n/a | try: |
|---|
| 411 | n/a | import ctypes |
|---|
| 412 | n/a | buffer = ctypes.create_string_buffer(300) |
|---|
| 413 | n/a | ctypes.windll.kernel32.GetSystemDirectoryA(buffer, 300) |
|---|
| 414 | n/a | dirs.insert(0, buffer.value.decode('mbcs')) |
|---|
| 415 | n/a | except: |
|---|
| 416 | n/a | pass |
|---|
| 417 | n/a | for dir in dirs: |
|---|
| 418 | n/a | try: |
|---|
| 419 | n/a | pipe = os.popen(os.path.join(dir, 'ipconfig') + ' /all') |
|---|
| 420 | n/a | except OSError: |
|---|
| 421 | n/a | continue |
|---|
| 422 | n/a | with pipe: |
|---|
| 423 | n/a | for line in pipe: |
|---|
| 424 | n/a | value = line.split(':')[-1].strip().lower() |
|---|
| 425 | n/a | if re.match('([0-9a-f][0-9a-f]-){5}[0-9a-f][0-9a-f]', value): |
|---|
| 426 | n/a | return int(value.replace('-', ''), 16) |
|---|
| 427 | n/a | |
|---|
| 428 | n/a | def _netbios_getnode(): |
|---|
| 429 | n/a | """Get the hardware address on Windows using NetBIOS calls. |
|---|
| 430 | n/a | See http://support.microsoft.com/kb/118623 for details.""" |
|---|
| 431 | n/a | import win32wnet, netbios |
|---|
| 432 | n/a | ncb = netbios.NCB() |
|---|
| 433 | n/a | ncb.Command = netbios.NCBENUM |
|---|
| 434 | n/a | ncb.Buffer = adapters = netbios.LANA_ENUM() |
|---|
| 435 | n/a | adapters._pack() |
|---|
| 436 | n/a | if win32wnet.Netbios(ncb) != 0: |
|---|
| 437 | n/a | return |
|---|
| 438 | n/a | adapters._unpack() |
|---|
| 439 | n/a | for i in range(adapters.length): |
|---|
| 440 | n/a | ncb.Reset() |
|---|
| 441 | n/a | ncb.Command = netbios.NCBRESET |
|---|
| 442 | n/a | ncb.Lana_num = ord(adapters.lana[i]) |
|---|
| 443 | n/a | if win32wnet.Netbios(ncb) != 0: |
|---|
| 444 | n/a | continue |
|---|
| 445 | n/a | ncb.Reset() |
|---|
| 446 | n/a | ncb.Command = netbios.NCBASTAT |
|---|
| 447 | n/a | ncb.Lana_num = ord(adapters.lana[i]) |
|---|
| 448 | n/a | ncb.Callname = '*'.ljust(16) |
|---|
| 449 | n/a | ncb.Buffer = status = netbios.ADAPTER_STATUS() |
|---|
| 450 | n/a | if win32wnet.Netbios(ncb) != 0: |
|---|
| 451 | n/a | continue |
|---|
| 452 | n/a | status._unpack() |
|---|
| 453 | n/a | bytes = status.adapter_address[:6] |
|---|
| 454 | n/a | if len(bytes) != 6: |
|---|
| 455 | n/a | continue |
|---|
| 456 | n/a | return int.from_bytes(bytes, 'big') |
|---|
| 457 | n/a | |
|---|
| 458 | n/a | # Thanks to Thomas Heller for ctypes and for his help with its use here. |
|---|
| 459 | n/a | |
|---|
| 460 | n/a | # If ctypes is available, use it to find system routines for UUID generation. |
|---|
| 461 | n/a | # XXX This makes the module non-thread-safe! |
|---|
| 462 | n/a | _uuid_generate_time = _UuidCreate = None |
|---|
| 463 | n/a | try: |
|---|
| 464 | n/a | import ctypes, ctypes.util |
|---|
| 465 | n/a | import sys |
|---|
| 466 | n/a | |
|---|
| 467 | n/a | # The uuid_generate_* routines are provided by libuuid on at least |
|---|
| 468 | n/a | # Linux and FreeBSD, and provided by libc on Mac OS X. |
|---|
| 469 | n/a | _libnames = ['uuid'] |
|---|
| 470 | n/a | if not sys.platform.startswith('win'): |
|---|
| 471 | n/a | _libnames.append('c') |
|---|
| 472 | n/a | for libname in _libnames: |
|---|
| 473 | n/a | try: |
|---|
| 474 | n/a | lib = ctypes.CDLL(ctypes.util.find_library(libname)) |
|---|
| 475 | n/a | except Exception: |
|---|
| 476 | n/a | continue |
|---|
| 477 | n/a | if hasattr(lib, 'uuid_generate_time'): |
|---|
| 478 | n/a | _uuid_generate_time = lib.uuid_generate_time |
|---|
| 479 | n/a | break |
|---|
| 480 | n/a | del _libnames |
|---|
| 481 | n/a | |
|---|
| 482 | n/a | # The uuid_generate_* functions are broken on MacOS X 10.5, as noted |
|---|
| 483 | n/a | # in issue #8621 the function generates the same sequence of values |
|---|
| 484 | n/a | # in the parent process and all children created using fork (unless |
|---|
| 485 | n/a | # those children use exec as well). |
|---|
| 486 | n/a | # |
|---|
| 487 | n/a | # Assume that the uuid_generate functions are broken from 10.5 onward, |
|---|
| 488 | n/a | # the test can be adjusted when a later version is fixed. |
|---|
| 489 | n/a | if sys.platform == 'darwin': |
|---|
| 490 | n/a | if int(os.uname().release.split('.')[0]) >= 9: |
|---|
| 491 | n/a | _uuid_generate_time = None |
|---|
| 492 | n/a | |
|---|
| 493 | n/a | # On Windows prior to 2000, UuidCreate gives a UUID containing the |
|---|
| 494 | n/a | # hardware address. On Windows 2000 and later, UuidCreate makes a |
|---|
| 495 | n/a | # random UUID and UuidCreateSequential gives a UUID containing the |
|---|
| 496 | n/a | # hardware address. These routines are provided by the RPC runtime. |
|---|
| 497 | n/a | # NOTE: at least on Tim's WinXP Pro SP2 desktop box, while the last |
|---|
| 498 | n/a | # 6 bytes returned by UuidCreateSequential are fixed, they don't appear |
|---|
| 499 | n/a | # to bear any relationship to the MAC address of any network device |
|---|
| 500 | n/a | # on the box. |
|---|
| 501 | n/a | try: |
|---|
| 502 | n/a | lib = ctypes.windll.rpcrt4 |
|---|
| 503 | n/a | except: |
|---|
| 504 | n/a | lib = None |
|---|
| 505 | n/a | _UuidCreate = getattr(lib, 'UuidCreateSequential', |
|---|
| 506 | n/a | getattr(lib, 'UuidCreate', None)) |
|---|
| 507 | n/a | except: |
|---|
| 508 | n/a | pass |
|---|
| 509 | n/a | |
|---|
| 510 | n/a | def _unixdll_getnode(): |
|---|
| 511 | n/a | """Get the hardware address on Unix using ctypes.""" |
|---|
| 512 | n/a | _buffer = ctypes.create_string_buffer(16) |
|---|
| 513 | n/a | _uuid_generate_time(_buffer) |
|---|
| 514 | n/a | return UUID(bytes=bytes_(_buffer.raw)).node |
|---|
| 515 | n/a | |
|---|
| 516 | n/a | def _windll_getnode(): |
|---|
| 517 | n/a | """Get the hardware address on Windows using ctypes.""" |
|---|
| 518 | n/a | _buffer = ctypes.create_string_buffer(16) |
|---|
| 519 | n/a | if _UuidCreate(_buffer) == 0: |
|---|
| 520 | n/a | return UUID(bytes=bytes_(_buffer.raw)).node |
|---|
| 521 | n/a | |
|---|
| 522 | n/a | def _random_getnode(): |
|---|
| 523 | n/a | """Get a random node ID, with eighth bit set as suggested by RFC 4122.""" |
|---|
| 524 | n/a | import random |
|---|
| 525 | n/a | return random.getrandbits(48) | 0x010000000000 |
|---|
| 526 | n/a | |
|---|
| 527 | n/a | _node = None |
|---|
| 528 | n/a | |
|---|
| 529 | n/a | def getnode(): |
|---|
| 530 | n/a | """Get the hardware address as a 48-bit positive integer. |
|---|
| 531 | n/a | |
|---|
| 532 | n/a | The first time this runs, it may launch a separate program, which could |
|---|
| 533 | n/a | be quite slow. If all attempts to obtain the hardware address fail, we |
|---|
| 534 | n/a | choose a random 48-bit number with its eighth bit set to 1 as recommended |
|---|
| 535 | n/a | in RFC 4122. |
|---|
| 536 | n/a | """ |
|---|
| 537 | n/a | |
|---|
| 538 | n/a | global _node |
|---|
| 539 | n/a | if _node is not None: |
|---|
| 540 | n/a | return _node |
|---|
| 541 | n/a | |
|---|
| 542 | n/a | import sys |
|---|
| 543 | n/a | if sys.platform == 'win32': |
|---|
| 544 | n/a | getters = [_windll_getnode, _netbios_getnode, _ipconfig_getnode] |
|---|
| 545 | n/a | else: |
|---|
| 546 | n/a | getters = [_unixdll_getnode, _ifconfig_getnode, _ip_getnode, |
|---|
| 547 | n/a | _arp_getnode, _lanscan_getnode, _netstat_getnode] |
|---|
| 548 | n/a | |
|---|
| 549 | n/a | for getter in getters + [_random_getnode]: |
|---|
| 550 | n/a | try: |
|---|
| 551 | n/a | _node = getter() |
|---|
| 552 | n/a | except: |
|---|
| 553 | n/a | continue |
|---|
| 554 | n/a | if _node is not None: |
|---|
| 555 | n/a | return _node |
|---|
| 556 | n/a | |
|---|
| 557 | n/a | _last_timestamp = None |
|---|
| 558 | n/a | |
|---|
| 559 | n/a | def uuid1(node=None, clock_seq=None): |
|---|
| 560 | n/a | """Generate a UUID from a host ID, sequence number, and the current time. |
|---|
| 561 | n/a | If 'node' is not given, getnode() is used to obtain the hardware |
|---|
| 562 | n/a | address. If 'clock_seq' is given, it is used as the sequence number; |
|---|
| 563 | n/a | otherwise a random 14-bit sequence number is chosen.""" |
|---|
| 564 | n/a | |
|---|
| 565 | n/a | # When the system provides a version-1 UUID generator, use it (but don't |
|---|
| 566 | n/a | # use UuidCreate here because its UUIDs don't conform to RFC 4122). |
|---|
| 567 | n/a | if _uuid_generate_time and node is clock_seq is None: |
|---|
| 568 | n/a | _buffer = ctypes.create_string_buffer(16) |
|---|
| 569 | n/a | _uuid_generate_time(_buffer) |
|---|
| 570 | n/a | return UUID(bytes=bytes_(_buffer.raw)) |
|---|
| 571 | n/a | |
|---|
| 572 | n/a | global _last_timestamp |
|---|
| 573 | n/a | import time |
|---|
| 574 | n/a | nanoseconds = int(time.time() * 1e9) |
|---|
| 575 | n/a | # 0x01b21dd213814000 is the number of 100-ns intervals between the |
|---|
| 576 | n/a | # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00. |
|---|
| 577 | n/a | timestamp = int(nanoseconds/100) + 0x01b21dd213814000 |
|---|
| 578 | n/a | if _last_timestamp is not None and timestamp <= _last_timestamp: |
|---|
| 579 | n/a | timestamp = _last_timestamp + 1 |
|---|
| 580 | n/a | _last_timestamp = timestamp |
|---|
| 581 | n/a | if clock_seq is None: |
|---|
| 582 | n/a | import random |
|---|
| 583 | n/a | clock_seq = random.getrandbits(14) # instead of stable storage |
|---|
| 584 | n/a | time_low = timestamp & 0xffffffff |
|---|
| 585 | n/a | time_mid = (timestamp >> 32) & 0xffff |
|---|
| 586 | n/a | time_hi_version = (timestamp >> 48) & 0x0fff |
|---|
| 587 | n/a | clock_seq_low = clock_seq & 0xff |
|---|
| 588 | n/a | clock_seq_hi_variant = (clock_seq >> 8) & 0x3f |
|---|
| 589 | n/a | if node is None: |
|---|
| 590 | n/a | node = getnode() |
|---|
| 591 | n/a | return UUID(fields=(time_low, time_mid, time_hi_version, |
|---|
| 592 | n/a | clock_seq_hi_variant, clock_seq_low, node), version=1) |
|---|
| 593 | n/a | |
|---|
| 594 | n/a | def uuid3(namespace, name): |
|---|
| 595 | n/a | """Generate a UUID from the MD5 hash of a namespace UUID and a name.""" |
|---|
| 596 | n/a | from hashlib import md5 |
|---|
| 597 | n/a | hash = md5(namespace.bytes + bytes(name, "utf-8")).digest() |
|---|
| 598 | n/a | return UUID(bytes=hash[:16], version=3) |
|---|
| 599 | n/a | |
|---|
| 600 | n/a | def uuid4(): |
|---|
| 601 | n/a | """Generate a random UUID.""" |
|---|
| 602 | n/a | return UUID(bytes=os.urandom(16), version=4) |
|---|
| 603 | n/a | |
|---|
| 604 | n/a | def uuid5(namespace, name): |
|---|
| 605 | n/a | """Generate a UUID from the SHA-1 hash of a namespace UUID and a name.""" |
|---|
| 606 | n/a | from hashlib import sha1 |
|---|
| 607 | n/a | hash = sha1(namespace.bytes + bytes(name, "utf-8")).digest() |
|---|
| 608 | n/a | return UUID(bytes=hash[:16], version=5) |
|---|
| 609 | n/a | |
|---|
| 610 | n/a | # The following standard UUIDs are for use with uuid3() or uuid5(). |
|---|
| 611 | n/a | |
|---|
| 612 | n/a | NAMESPACE_DNS = UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8') |
|---|
| 613 | n/a | NAMESPACE_URL = UUID('6ba7b811-9dad-11d1-80b4-00c04fd430c8') |
|---|
| 614 | n/a | NAMESPACE_OID = UUID('6ba7b812-9dad-11d1-80b4-00c04fd430c8') |
|---|
| 615 | n/a | NAMESPACE_X500 = UUID('6ba7b814-9dad-11d1-80b4-00c04fd430c8') |
|---|