Skip to content

Instantly share code, notes, and snippets.

@noahcoad
Created June 22, 2018 18:59
Show Gist options
  • Save noahcoad/a0e2490b81adccf9426b110899b09f4b to your computer and use it in GitHub Desktop.
Save noahcoad/a0e2490b81adccf9426b110899b09f4b to your computer and use it in GitHub Desktop.
Get the hardware serial number for Raspberry Pi or Mac in Python 3.6
import platform, re, subprocess, os.path, logging;
log = logging.getLogger('simple_example')
log.setLevel(logging.INFO)
# get local system serial identifier
# tested for Raspberry Pi and Mac OSX
def get_serial():
log.info("getting serial number")
ptn = None
# specify method per OS
if platform.system() == 'Linux':
ptn = ['linux', ['cat', '/proc/cpuinfo'], r'Serial\t\t: (\w*)']
elif platform.system() == 'Darwin' and platform.mac_ver()[0]:
ptn = ['osx', ['system_profiler', 'SPHardwareDataType'], r'Serial Number \(system\): (\w*)']
# if an OS was found
if ptn:
log.info('%s platform' % ptn[0])
procinfo = subprocess.run(ptn[1], stdout=subprocess.PIPE).stdout.decode('utf-8')
serial = re.search(ptn[2], procinfo).group(1)
else:
log.warning("error: system type not supported yet")
if serial: log.info("serial: %s" % serial)
return serial
print(get_serial())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment