def __call__(self, name, sam=KEY_READ):
"""Get a registry key::
registry(r"HKEY_LOCAL_MACHINE\\Software")
registry("HKEY_LOCAL_MACHINE")("Software")
:rtype: :class:`PyHKey`
"""
if name in self.registry_base_keys:
key = self.registry_base_keys[name]
if sam != key.sam:
key = key.reopen(sam)
return key
if "\\" not in name:
raise ValueError("Unknow registry base key <{0}>".format(name))
base_name, subkey = name.split("\\", 1)
if base_name not in self.registry_base_keys:
raise ValueError("Unknow registry base key <{0}>".format(base_name))
return self.registry_base_keys[base_name](subkey, sam)
python类KEY_READ的实例源码
def __get_data(root_key, key, value):
"""This method gets the data from the given key and value under the root
key.
Args:
root_key (str): The root key as abbreviated string.
Valid values: [hklm, hkcr, hkcu, hku, hkpd, hkcc].
key (str): The subkey starting from the root key.
e.g.: SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
value (str): The value to query.
Returns:
Str. It returns the retrieved data, or an empty string if data could not be retrieved.
"""
data = ''
try:
hkey = _winreg.OpenKey(root_key, key, 0, _winreg.KEY_READ)
data, regtype = _winreg.QueryValueEx(hkey, value)
_winreg.CloseKey(hkey)
except WindowsError as e:
logging.error('Error occurred getting registry data: {0}'.format(e))
return data
def getEnvironment(scope, name):
assert scope in ('user', 'system')
value = ''
if platform.system() == 'Windows':
root, subkey = getWindowsEnvironmentKey(scope)
key = winreg.OpenKey(root, subkey, 0, winreg.KEY_READ)
try:
value, _ = winreg.QueryValueEx(key, name)
except WindowsError:
value = ''
else:
if name.lower() == 'uid':
return str(os.geteuid())
if len(os_user_name) > 0:
ret, cret = syscommand('su -l %s -c \'echo ${%s}\'' % (os_user_name, name), True)
if len(ret) > 0:
value = ret[0].strip()
else:
value = os.environ.get(name, "")
return value
def loadFromRegistryCurrentUser(self):
''' Load configuration from Windows registry. '''
# We manually build a .INI file in memory from the registry.
inilines = ['[%s]' % applicationConfig.CONFIG_SECTIONNAME]
try:
import _winreg
except ImportError, exc:
raise ImportError, "applicationConfig.loadFromRegistryCurrentUser() can only be used under Windows (requires the _winreg module).\nCould not import module because: %s" % exc
try:
key = _winreg.OpenKey(
_winreg.HKEY_CURRENT_USER, applicationConfig.CONFIG_REGPATH, 0, _winreg.KEY_READ)
# Now get all values in this key:
i = 0
try:
while True:
# mmm..strange, Should unpack to 3 values, but seems to
# unpack to more. Bug of EnumValue() ?
valueobj = _winreg.EnumValue(key, i)
valuename = str(valueobj[0]).strip()
valuedata = str(valueobj[1]).strip()
valuetype = valueobj[2]
if valuetype != _winreg.REG_SZ:
raise TypeError, "The registry value %s does not have the correct type (REG_SZ). Please delete it." % valuename
else:
if valuename not in applicationConfig.NONEXPORTABLE_PARAMETERS:
# Build the .INI file.
inilines += ['%s=%s' % (valuename, str(valuedata))]
i += 1
except EnvironmentError:
# EnvironmentError means: "No more values to read". We simply
# exit the 'While True' loop.
pass
# Then parse the generated .INI file.
self.fromINI('\n'.join(inilines))
except EnvironmentError:
raise WindowsError, "Could not read configuration from registry !"
_winreg.CloseKey(key)
def onUninstall():
path = os.path.join(config.getUserDefaultConfigPath(), ".dbInstall")
if os.path.exists(path):
#This is an update. Bail.
os.remove(path)
return
key = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER, "Environment", 0, _winreg.KEY_READ | _winreg.KEY_WRITE)
try:
value, typ = _winreg.QueryValueEx(key, "Path")
except:
return
if value is None or value == "":
return
dir = os.path.dirname(__file__)
if not isinstance(dir, unicode):
dir = dir.decode(sys.getfilesystemencoding())
dir = dir.replace(addonHandler.DELETEDIR_SUFFIX, "")
if value.find(dir) != -1:
value = value.replace(";" + dir, "")
value = value.replace(dir + ";", "")
value = value.replace(dir, "")
_winreg.SetValueEx(key, "Path", None, typ, value)
sendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, u"Environment")
def __init__(self, surkey, name, sam=KEY_READ):
self.surkey = surkey
self.name = name
self.fullname = self.surkey.fullname + "\\" + self.name if self.name else self.surkey.name
self.sam = sam
self._phkey = None
#self.phkey
def getenv(self, name):
key = winreg.OpenKey(self.root, self.subkey, 0, winreg.KEY_READ)
try:
value, _ = winreg.QueryValueEx(key, name)
except WindowsError:
value = ''
winreg.CloseKey(key)
return value
def _reg_query_sub_keys(handle, key, keylist = []):
reghandle = reg.OpenKey(handle, key, 0, reg.KEY_READ)
try:
i = 0
while True:
subkey = reg.EnumKey(reghandle, i)
i += 1
_reg_query_sub_keys(handle, key + subkey + "\\", keylist)
except WindowsError as ex:
if ex.winerror == 259:
keylist.append(key)
finally:
reg.CloseKey(reghandle)
def read_registry(key, valueex):
reg_key = OpenKey(HKEY_LOCAL_MACHINE, key, 0, KEY_READ)
return QueryValueEx(reg_key, valueex)
def __get_key_values(root_key, key):
"""This method gets the values and subkeys from the given key under the
root key.
Args:
root_key (str): The root key as abbreviated string.
Valid values: [hklm, hkcr, hkcu, hku, hkpd, hkcc].
key (str): The subkey starting from the root key.
e.g.: SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\interfaces
Returns:
list. It returns the retrieved values and subkeys
or an empty list if data could not be retrieved.
"""
values = []
i = 0
try:
hkey = _winreg.OpenKey(root_key, key, 0, _winreg.KEY_READ)
except WindowsError as e:
logging.error('Key ({0}) could not be opened: {1}'.format(key, e))
return values
while True:
try:
value = _winreg.EnumKey(hkey, i)
values.append(value)
i += 1
except WindowsError:
logging.info('No more values. Total values: {0}'.format(i))
if hkey:
_winreg.CloseKey(hkey)
break # no more values
return values
def _get_uid(self):
hKey = regedit.OpenKey(regedit.HKEY_LOCAL_MACHINE,
r"SOFTWARE\\Microsoft\\Cryptography", 0,
regedit.KEY_READ | regedit.KEY_WOW64_64KEY)
value, _ = regedit.QueryValueEx(hKey, "MachineGuid")
return value
def wpkg_running():
running = None
try:
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, R"SOFTWARE\WPKG", 0, _winreg.KEY_READ | _winreg.KEY_WOW64_64KEY)
running = _winreg.QueryValueEx(key, "running")[0]
_winreg.CloseKey(key)
except WindowsError:
pass
if running == 'true':
return True
else:
return False
def wpkggp_version(version):
req_version = version
try:
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, R"SOFTWARE\Wpkg-Gp", 0, _winreg.KEY_READ | _winreg.KEY_WOW64_64KEY)
inst_version = _winreg.QueryValueEx(key, "DisplayVersion")[0]
_winreg.CloseKey(key)
except WindowsError:
inst_version = None
return False
if parse_version(req_version) <= parse_version(inst_version):
return True
else:
return False
def ReadLastSyncTime():
with _winreg.CreateKeyEx(_winreg.HKEY_LOCAL_MACHINE, R"SOFTWARE\WPKG", 0,
_winreg.KEY_READ | _winreg.KEY_WOW64_64KEY) as key:
try:
last_sync_value = _winreg.QueryValueEx(key, "lastsync")[0]
except WindowsError:
return None
try:
last_sync_time = datetime.datetime.strptime(last_sync_value, '%Y-%m-%d %H:%M:%S')
except (ValueError, TypeError):
return None
return last_sync_time
def readName(keyPath, name):
# return the value of single path and name
explorer = OpenKey(HKEY_LOCAL_MACHINE,keyPath, 0, KEY_READ | KEY_WOW64_64KEY)
return str(QueryValueEx(explorer, name)[0])
def readValues(keyPath):
# return Dict of name:value from key
explorer = OpenKey(HKEY_LOCAL_MACHINE, keyPath, 0, KEY_READ | KEY_WOW64_64KEY)
valuesDict = {}
for i in range(QueryInfoKey(explorer)[1]):
name, value, type = EnumValue(explorer, i)
valuesDict[name] = value
return valuesDict
def readKeys(keyPath):
# return list of Keys
explorer = OpenKey(HKEY_LOCAL_MACHINE, keyPath, 0, KEY_READ | KEY_WOW64_64KEY)
KeysList = []
for i in xrange(QueryInfoKey(explorer)[0]):
name = EnumKey(explorer, i)
KeysList.append(name)
return KeysList
def __init__(self, keyhandle = _winreg.HKEY_LOCAL_MACHINE, keypath = [], flags = _winreg.KEY_READ):
"""If flags=None, then it will create the key.. otherwise pass a _winreg.KEY_* sam"""
self.keyhandle = None
self.open(keyhandle, keypath, flags)
def onInstall(postPathBug = False):
#Add ourself to the path, so that commands when spoken can be queried to us.
#Only if we are truely installing though.
addons = []
if not postPathBug:
addons = addonHandler.getAvailableAddons()
for addon in addons:
if addon.name=="DictationBridge":
#Hack to work around condition where
#the uninstaller removes this addon from the path
#After the installer for the updator ran.
#We could use version specific directories, but wsr macros Does not
#play nice with refreshing the path environment after path updates,
# requiring a complete reboot of wsr, or commands spontaneously break cripticly.
with open(os.path.join(config.getUserDefaultConfigPath(), ".dbInstall"),
"w") as fi:
fi.write("dbInstall")
return
key = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER, "Environment", 0, _winreg.KEY_READ | _winreg.KEY_WRITE)
try:
value, typ = _winreg.QueryValueEx(key, "Path")
except:
value, typ = None, _winreg.REG_EXPAND_SZ
if value is None:
value = ""
dir = os.path.dirname(__file__)
if not isinstance(dir, unicode):
dir = dir.decode(sys.getfilesystemencoding())
dir = dir.replace(addonHandler.ADDON_PENDINGINSTALL_SUFFIX, "")
log.info("addon directory: %r" % dir)
log.info("current PATH: %r" % value)
if value.lower().find(dir.lower()) == -1:
if value != "":
value += ";"
value += dir
log.info("new PATH: %r" % value)
_winreg.SetValueEx(key, "Path", None, typ, value)
sendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, u"Environment")
def get_machine_id():
global _machine_id
rv = _machine_id
if rv is not None:
return rv
def _generate():
# Potential sources of secret information on linux. The machine-id
# is stable across boots, the boot id is not
for filename in '/etc/machine-id', '/proc/sys/kernel/random/boot_id':
try:
with open(filename, 'rb') as f:
return f.readline().strip()
except IOError:
continue
# On OS X we can use the computer's serial number assuming that
# ioreg exists and can spit out that information.
try:
# Also catch import errors: subprocess may not be available, e.g.
# Google App Engine
# See https://github.com/pallets/werkzeug/issues/925
from subprocess import Popen, PIPE
dump = Popen(['ioreg', '-c', 'IOPlatformExpertDevice', '-d', '2'],
stdout=PIPE).communicate()[0]
match = re.search(b'"serial-number" = <([^>]+)', dump)
if match is not None:
return match.group(1)
except (OSError, ImportError):
pass
# On Windows we can use winreg to get the machine guid
wr = None
try:
import winreg as wr
except ImportError:
try:
import _winreg as wr
except ImportError:
pass
if wr is not None:
try:
with wr.OpenKey(wr.HKEY_LOCAL_MACHINE,
'SOFTWARE\\Microsoft\\Cryptography', 0,
wr.KEY_READ | wr.KEY_WOW64_64KEY) as rk:
return wr.QueryValueEx(rk, 'MachineGuid')[0]
except WindowsError:
pass
_machine_id = rv = _generate()
return rv
def get_machine_id():
global _machine_id
rv = _machine_id
if rv is not None:
return rv
def _generate():
# Potential sources of secret information on linux. The machine-id
# is stable across boots, the boot id is not
for filename in '/etc/machine-id', '/proc/sys/kernel/random/boot_id':
try:
with open(filename, 'rb') as f:
f.readline().strip()
except IOError:
continue
# On OS X we can use the computer's serial number assuming that
# ioreg exists and can spit out that information.
from subprocess import Popen, PIPE
try:
dump = Popen(['ioreg', '-c', 'IOPlatformExpertDevice', '-d', '2'],
stdout=PIPE).communicate()[0]
match = re.search(b'"serial-number" = <([^>]+)', dump)
if match is not None:
return match.group(1)
except OSError:
pass
# On Windows we can use winreg to get the machine guid
wr = None
try:
import winreg as wr
except ImportError:
try:
import _winreg as wr
except ImportError:
pass
if wr is not None:
try:
with wr.OpenKey(wr.HKEY_LOCAL_MACHINE,
'SOFTWARE\\Microsoft\\Cryptography', 0,
wr.KEY_READ | wr.KEY_WOW64_64KEY) as rk:
return wr.QueryValueEx(rk, 'MachineGuid')[0]
except WindowsError:
pass
_machine_id = rv = _generate()
return rv
def get_machine_id():
global _machine_id
rv = _machine_id
if rv is not None:
return rv
def _generate():
# Potential sources of secret information on linux. The machine-id
# is stable across boots, the boot id is not
for filename in '/etc/machine-id', '/proc/sys/kernel/random/boot_id':
try:
with open(filename, 'rb') as f:
return f.readline().strip()
except IOError:
continue
# On OS X we can use the computer's serial number assuming that
# ioreg exists and can spit out that information.
try:
# Also catch import errors: subprocess may not be available, e.g.
# Google App Engine
# See https://github.com/pallets/werkzeug/issues/925
from subprocess import Popen, PIPE
dump = Popen(['ioreg', '-c', 'IOPlatformExpertDevice', '-d', '2'],
stdout=PIPE).communicate()[0]
match = re.search(b'"serial-number" = <([^>]+)', dump)
if match is not None:
return match.group(1)
except (OSError, ImportError):
pass
# On Windows we can use winreg to get the machine guid
wr = None
try:
import winreg as wr
except ImportError:
try:
import _winreg as wr
except ImportError:
pass
if wr is not None:
try:
with wr.OpenKey(wr.HKEY_LOCAL_MACHINE,
'SOFTWARE\\Microsoft\\Cryptography', 0,
wr.KEY_READ | wr.KEY_WOW64_64KEY) as rk:
return wr.QueryValueEx(rk, 'MachineGuid')[0]
except WindowsError:
pass
_machine_id = rv = _generate()
return rv
def get_machine_id():
global _machine_id
rv = _machine_id
if rv is not None:
return rv
def _generate():
# Potential sources of secret information on linux. The machine-id
# is stable across boots, the boot id is not
for filename in '/etc/machine-id', '/proc/sys/kernel/random/boot_id':
try:
with open(filename, 'rb') as f:
return f.readline().strip()
except IOError:
continue
# On OS X we can use the computer's serial number assuming that
# ioreg exists and can spit out that information.
try:
# Also catch import errors: subprocess may not be available, e.g.
# Google App Engine
# See https://github.com/pallets/werkzeug/issues/925
from subprocess import Popen, PIPE
dump = Popen(['ioreg', '-c', 'IOPlatformExpertDevice', '-d', '2'],
stdout=PIPE).communicate()[0]
match = re.search(b'"serial-number" = <([^>]+)', dump)
if match is not None:
return match.group(1)
except (OSError, ImportError):
pass
# On Windows we can use winreg to get the machine guid
wr = None
try:
import winreg as wr
except ImportError:
try:
import _winreg as wr
except ImportError:
pass
if wr is not None:
try:
with wr.OpenKey(wr.HKEY_LOCAL_MACHINE,
'SOFTWARE\\Microsoft\\Cryptography', 0,
wr.KEY_READ | wr.KEY_WOW64_64KEY) as rk:
return wr.QueryValueEx(rk, 'MachineGuid')[0]
except WindowsError:
pass
_machine_id = rv = _generate()
return rv
def get_machine_id():
global _machine_id
rv = _machine_id
if rv is not None:
return rv
def _generate():
# Potential sources of secret information on linux. The machine-id
# is stable across boots, the boot id is not
for filename in '/etc/machine-id', '/proc/sys/kernel/random/boot_id':
try:
with open(filename, 'rb') as f:
return f.readline().strip()
except IOError:
continue
# On OS X we can use the computer's serial number assuming that
# ioreg exists and can spit out that information.
try:
# Also catch import errors: subprocess may not be available, e.g.
# Google App Engine
# See https://github.com/pallets/werkzeug/issues/925
from subprocess import Popen, PIPE
dump = Popen(['ioreg', '-c', 'IOPlatformExpertDevice', '-d', '2'],
stdout=PIPE).communicate()[0]
match = re.search(b'"serial-number" = <([^>]+)', dump)
if match is not None:
return match.group(1)
except (OSError, ImportError):
pass
# On Windows we can use winreg to get the machine guid
wr = None
try:
import winreg as wr
except ImportError:
try:
import _winreg as wr
except ImportError:
pass
if wr is not None:
try:
with wr.OpenKey(wr.HKEY_LOCAL_MACHINE,
'SOFTWARE\\Microsoft\\Cryptography', 0,
wr.KEY_READ | wr.KEY_WOW64_64KEY) as rk:
return wr.QueryValueEx(rk, 'MachineGuid')[0]
except WindowsError:
pass
_machine_id = rv = _generate()
return rv
def get_machine_id():
global _machine_id
rv = _machine_id
if rv is not None:
return rv
def _generate():
# Potential sources of secret information on linux. The machine-id
# is stable across boots, the boot id is not
for filename in '/etc/machine-id', '/proc/sys/kernel/random/boot_id':
try:
with open(filename, 'rb') as f:
return f.readline().strip()
except IOError:
continue
# On OS X we can use the computer's serial number assuming that
# ioreg exists and can spit out that information.
try:
# Also catch import errors: subprocess may not be available, e.g.
# Google App Engine
# See https://github.com/pallets/werkzeug/issues/925
from subprocess import Popen, PIPE
dump = Popen(['ioreg', '-c', 'IOPlatformExpertDevice', '-d', '2'],
stdout=PIPE).communicate()[0]
match = re.search(b'"serial-number" = <([^>]+)', dump)
if match is not None:
return match.group(1)
except (OSError, ImportError):
pass
# On Windows we can use winreg to get the machine guid
wr = None
try:
import winreg as wr
except ImportError:
try:
import _winreg as wr
except ImportError:
pass
if wr is not None:
try:
with wr.OpenKey(wr.HKEY_LOCAL_MACHINE,
'SOFTWARE\\Microsoft\\Cryptography', 0,
wr.KEY_READ | wr.KEY_WOW64_64KEY) as rk:
return wr.QueryValueEx(rk, 'MachineGuid')[0]
except WindowsError:
pass
_machine_id = rv = _generate()
return rv
def get_machine_id():
global _machine_id
rv = _machine_id
if rv is not None:
return rv
def _generate():
# Potential sources of secret information on linux. The machine-id
# is stable across boots, the boot id is not
for filename in '/etc/machine-id', '/proc/sys/kernel/random/boot_id':
try:
with open(filename, 'rb') as f:
return f.readline().strip()
except IOError:
continue
# On OS X we can use the computer's serial number assuming that
# ioreg exists and can spit out that information.
try:
# Also catch import errors: subprocess may not be available, e.g.
# Google App Engine
# See https://github.com/pallets/werkzeug/issues/925
from subprocess import Popen, PIPE
dump = Popen(['ioreg', '-c', 'IOPlatformExpertDevice', '-d', '2'],
stdout=PIPE).communicate()[0]
match = re.search(b'"serial-number" = <([^>]+)', dump)
if match is not None:
return match.group(1)
except (OSError, ImportError):
pass
# On Windows we can use winreg to get the machine guid
wr = None
try:
import winreg as wr
except ImportError:
try:
import _winreg as wr
except ImportError:
pass
if wr is not None:
try:
with wr.OpenKey(wr.HKEY_LOCAL_MACHINE,
'SOFTWARE\\Microsoft\\Cryptography', 0,
wr.KEY_READ | wr.KEY_WOW64_64KEY) as rk:
return wr.QueryValueEx(rk, 'MachineGuid')[0]
except WindowsError:
pass
_machine_id = rv = _generate()
return rv
def get_machine_id():
global _machine_id
rv = _machine_id
if rv is not None:
return rv
def _generate():
# Potential sources of secret information on linux. The machine-id
# is stable across boots, the boot id is not
for filename in '/etc/machine-id', '/proc/sys/kernel/random/boot_id':
try:
with open(filename, 'rb') as f:
return f.readline().strip()
except IOError:
continue
# On OS X we can use the computer's serial number assuming that
# ioreg exists and can spit out that information.
try:
# Also catch import errors: subprocess may not be available, e.g.
# Google App Engine
# See https://github.com/pallets/werkzeug/issues/925
from subprocess import Popen, PIPE
dump = Popen(['ioreg', '-c', 'IOPlatformExpertDevice', '-d', '2'],
stdout=PIPE).communicate()[0]
match = re.search(b'"serial-number" = <([^>]+)', dump)
if match is not None:
return match.group(1)
except (OSError, ImportError):
pass
# On Windows we can use winreg to get the machine guid
wr = None
try:
import winreg as wr
except ImportError:
try:
import _winreg as wr
except ImportError:
pass
if wr is not None:
try:
with wr.OpenKey(wr.HKEY_LOCAL_MACHINE,
'SOFTWARE\\Microsoft\\Cryptography', 0,
wr.KEY_READ | wr.KEY_WOW64_64KEY) as rk:
return wr.QueryValueEx(rk, 'MachineGuid')[0]
except WindowsError:
pass
_machine_id = rv = _generate()
return rv
def get_machine_id():
global _machine_id
rv = _machine_id
if rv is not None:
return rv
def _generate():
# Potential sources of secret information on linux. The machine-id
# is stable across boots, the boot id is not
for filename in '/etc/machine-id', '/proc/sys/kernel/random/boot_id':
try:
with open(filename, 'rb') as f:
return f.readline().strip()
except IOError:
continue
# On OS X we can use the computer's serial number assuming that
# ioreg exists and can spit out that information.
try:
# Also catch import errors: subprocess may not be available, e.g.
# Google App Engine
# See https://github.com/pallets/werkzeug/issues/925
from subprocess import Popen, PIPE
dump = Popen(['ioreg', '-c', 'IOPlatformExpertDevice', '-d', '2'],
stdout=PIPE).communicate()[0]
match = re.search(b'"serial-number" = <([^>]+)', dump)
if match is not None:
return match.group(1)
except (OSError, ImportError):
pass
# On Windows we can use winreg to get the machine guid
wr = None
try:
import winreg as wr
except ImportError:
try:
import _winreg as wr
except ImportError:
pass
if wr is not None:
try:
with wr.OpenKey(wr.HKEY_LOCAL_MACHINE,
'SOFTWARE\\Microsoft\\Cryptography', 0,
wr.KEY_READ | wr.KEY_WOW64_64KEY) as rk:
return wr.QueryValueEx(rk, 'MachineGuid')[0]
except WindowsError:
pass
_machine_id = rv = _generate()
return rv
def get_machine_id():
global _machine_id
rv = _machine_id
if rv is not None:
return rv
def _generate():
# Potential sources of secret information on linux. The machine-id
# is stable across boots, the boot id is not
for filename in '/etc/machine-id', '/proc/sys/kernel/random/boot_id':
try:
with open(filename, 'rb') as f:
return f.readline().strip()
except IOError:
continue
# On OS X we can use the computer's serial number assuming that
# ioreg exists and can spit out that information.
try:
# Also catch import errors: subprocess may not be available, e.g.
# Google App Engine
# See https://github.com/pallets/werkzeug/issues/925
from subprocess import Popen, PIPE
dump = Popen(['ioreg', '-c', 'IOPlatformExpertDevice', '-d', '2'],
stdout=PIPE).communicate()[0]
match = re.search(b'"serial-number" = <([^>]+)', dump)
if match is not None:
return match.group(1)
except (OSError, ImportError):
pass
# On Windows we can use winreg to get the machine guid
wr = None
try:
import winreg as wr
except ImportError:
try:
import _winreg as wr
except ImportError:
pass
if wr is not None:
try:
with wr.OpenKey(wr.HKEY_LOCAL_MACHINE,
'SOFTWARE\\Microsoft\\Cryptography', 0,
wr.KEY_READ | wr.KEY_WOW64_64KEY) as rk:
return wr.QueryValueEx(rk, 'MachineGuid')[0]
except WindowsError:
pass
_machine_id = rv = _generate()
return rv
def get_machine_id():
global _machine_id
rv = _machine_id
if rv is not None:
return rv
def _generate():
# Potential sources of secret information on linux. The machine-id
# is stable across boots, the boot id is not
for filename in '/etc/machine-id', '/proc/sys/kernel/random/boot_id':
try:
with open(filename, 'rb') as f:
return f.readline().strip()
except IOError:
continue
# On OS X we can use the computer's serial number assuming that
# ioreg exists and can spit out that information.
try:
# Also catch import errors: subprocess may not be available, e.g.
# Google App Engine
# See https://github.com/pallets/werkzeug/issues/925
from subprocess import Popen, PIPE
dump = Popen(['ioreg', '-c', 'IOPlatformExpertDevice', '-d', '2'],
stdout=PIPE).communicate()[0]
match = re.search(b'"serial-number" = <([^>]+)', dump)
if match is not None:
return match.group(1)
except (OSError, ImportError):
pass
# On Windows we can use winreg to get the machine guid
wr = None
try:
import winreg as wr
except ImportError:
try:
import _winreg as wr
except ImportError:
pass
if wr is not None:
try:
with wr.OpenKey(wr.HKEY_LOCAL_MACHINE,
'SOFTWARE\\Microsoft\\Cryptography', 0,
wr.KEY_READ | wr.KEY_WOW64_64KEY) as rk:
return wr.QueryValueEx(rk, 'MachineGuid')[0]
except WindowsError:
pass
_machine_id = rv = _generate()
return rv