简体   繁体   中英

Using Python to find Mac UUID/Serial Number

Basically I was planning on tying the computers UUID/Serial number to the key which it is ran with, On windows I found getting the UUID easy enough however I am struggling to get anything for Mac. Any solutions?

MacOS has a built-in program for accessing this information and you can fetch it with

system_profiler SPHardwareDataType | grep 'Serial Number' | awk '{print $4}'

If you explicitly needed this string inside python (and if you're using 3.5+) you could use the subprocess module

import subprocess
cmd = "system_profiler SPHardwareDataType | grep 'Serial Number' | awk '{print $4}'"
result = subprocess.run(cmd, stdout=subprocess.PIPE, shell=True, check=True)
serial_number = result.stdout.strip()

Here's how I'm getting Mac serials via Python:

import subprocess

task = subprocess.Popen(
    ['system_profiler', 'SPHardwareDataType'],
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE
)

out, err = task.communicate()

for l in out.split('\n'):
    if 'Serial Number (system)' in l:
        serial_line = l.strip()
        break

serial = serial_line.split(' ')[-1]

print(serial)

Edit: I've found a method that is shorter and that I like a lot more than a line split loop.

import json
import subprocess
system_profile_data = subprocess.Popen(
    ['system_profiler', '-json', 'SPHardwareDataType'], stdout=subprocess.PIPE)
data = json.loads(system_profile_data.stdout.read())
serial = data.get('SPHardwareDataType', {})[0].get('serial_number')
print(serial)

A pyobjc way can be found here: https://gist.github.com/pudquick/c7dd1262bd81a32663f0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM