def __init__(self):
self.hkey={}
for key in (k for k in dir(reg) if k.startswith('HKEY_')):
try:
chk = reg.ConnectRegistry(None, getattr(reg, key))
inf = reg.QueryInfoKey(chk)
reg.CloseKey(chk)
except WindowsError: pass # some keys may appear in _winreg but can't be reached
else:
hk = Hkey(key)
try:
chk=hk.keys
except WindowsError: pass # some keys can be accessed but not enumerated
else: # some keys work fine ...
name=key[5:].lower()
self.hkey[name]=hk # for iterating
setattr(self, name, hk) # for easy access
python类ConnectRegistry()的实例源码
def __init__(self, **kwargs):
'Initialize the Key object.'
assert kwargs, 'No Keyword Arguments Were Found'
self.__repr, key, sub_key, sam, computer_name = '%s(%s)' % (self.__class__.__name__, ', '.join(['%s=%r' % (key, kwargs[key]) for key in kwargs])), kwargs.pop('key', None), kwargs.pop('sub_key', None), kwargs.pop('sam', None), kwargs.pop('computer_name', None)
assert not kwargs, 'Invalid Keyword Arguments Were Found'
if isinstance(key, (int, _winreg.HKEYType)) and sub_key is None and sam is None and computer_name is None:
self.__self = _winreg.OpenKey(key, '')
elif isinstance(key, Key) and sub_key is None and sam is None and computer_name is None:
self.__self = _winreg.OpenKey(key.__self, '')
elif isinstance(key, (int, _winreg.HKEYType)) and isinstance(sub_key, str) and sam is None and computer_name is None:
self.__self = _winreg.OpenKey(key, sub_key)
elif isinstance(key, Key) and isinstance(sub_key, str) and sam is None and computer_name is None:
self.__self = _winreg.OpenKey(key.__self, sub_key)
elif isinstance(key, (int, _winreg.HKEYType)) and sub_key is None and isinstance(sam, int) and computer_name is None:
self.__self = _winreg.OpenKey(key, '', 0, sam)
elif isinstance(key, Key) and sub_key is None and isinstance(sam, int) and computer_name is None:
self.__self = _winreg.OpenKey(key.__self, '', 0, sam)
elif isinstance(key, (int, _winreg.HKEYType)) and isinstance(sub_key, str) and isinstance(sam, int) and computer_name is None:
self.__self = _winreg.OpenKey(key, sub_key, 0, sam)
elif isinstance(key, Key) and isinstance(sub_key, str) and isinstance(sam, int) and computer_name is None:
self.__self = _winreg.OpenKey(key.__self, sub_key, 0, sam)
elif isinstance(key, int) and sub_key is None and sam is None and isinstance(computer_name, str):
self.__self = _winreg.ConnectRegistry(computer_name, key)
elif isinstance(key, int) and isinstance(sub_key, str) and sam is None and isinstance(computer_name, str):
self.__self = _winreg.OpenKey(_winreg.ConnectRegistry(computer_name, key), sub_key)
elif isinstance(key, int) and sub_key is None and isinstance(sam, int) and isinstance(computer_name, str):
self.__self = _winreg.OpenKey(_winreg.ConnectRegistry(computer_name, key), '', 0, sam)
elif isinstance(key, int) and isinstance(sub_key, str) and isinstance(sam, int) and isinstance(computer_name, str):
self.__self = _winreg.OpenKey(_winreg.ConnectRegistry(computer_name, key), sub_key, 0, sam)
else:
raise TypeError, 'Key Could Not Be Initialized'
def __init__(self, name):
self.parent=None
self.level=0
self.name=name
self.wrk=reg.ConnectRegistry(None, getattr(reg, name))
self._keys=None
self._vals=None
def __init__(self, key, subkey=None, mode=None, computer=None):
'Initialize the Key object.'
if isinstance(key, (int, _winreg.HKEYType)) and subkey is None and mode is None and computer is None:
self.__key = _winreg.OpenKey(key, '')
elif isinstance(key, Key) and subkey is None and mode is None and computer is None:
self.__key = _winreg.OpenKey(key.__key, '')
elif isinstance(key, (int, _winreg.HKEYType)) and isinstance(subkey, str) and mode is None and computer is None:
self.__key = _winreg.OpenKey(key, subkey)
elif isinstance(key, Key) and isinstance(subkey, str) and mode is None and computer is None:
self.__key = _winreg.OpenKey(key.__key, subkey)
elif isinstance(key, (int, _winreg.HKEYType)) and subkey is None and isinstance(mode, int) and computer is None:
self.__key = _winreg.OpenKey(key, '', 0, mode)
elif isinstance(key, Key) and subkey is None and isinstance(mode, int) and computer is None:
self.__key = _winreg.OpenKey(key.__key, '', 0, mode)
elif isinstance(key, (int, _winreg.HKEYType)) and isinstance(subkey, str) and isinstance(mode, int) and computer is None:
self.__key = _winreg.OpenKey(key, subkey, 0, mode)
elif isinstance(key, Key) and isinstance(subkey, str) and isinstance(mode, int) and computer is None:
self.__key = _winreg.OpenKey(key.__key, subkey, 0, mode)
elif isinstance(key, int) and subkey is None and mode is None and isinstance(computer, str):
self.__key = _winreg.ConnectRegistry(computer, key)
elif isinstance(key, int) and isinstance(subkey, str) and mode is None and isinstance(computer, str):
self.__key = _winreg.OpenKey(_winreg.ConnectRegistry(computer, key), subkey)
elif isinstance(key, int) and subkey is None and isinstance(mode, int) and isinstance(computer, str):
self.__key = _winreg.OpenKey(_winreg.ConnectRegistry(computer, key), '', 0, mode)
elif isinstance(key, int) and isinstance(subkey, str) and isinstance(mode, int) and isinstance(computer, str):
self.__key = _winreg.OpenKey(_winreg.ConnectRegistry(computer, key), subkey, 0, mode)
else:
raise TypeError, 'Please check documentation.'
self.__keys = Keys(self.__key)
self.__values = Values(self.__key)
self.__info = Info(self.__key)
self.__repr = 'Key(%s)' % ', '.join([repr(key)] + ['%s=%r' % (key, value) for key, value in zip(('subkey', 'mode', 'computer'), (subkey, mode, computer)) if value is not None])
def __init__(self, key, subkey=None, mode=None, computer=None):
'Initialize the Key object.'
if isinstance(key, (int, _winreg.HKEYType)) and subkey is None and mode is None and computer is None:
self.__key = _winreg.OpenKey(key, '')
elif isinstance(key, Key) and subkey is None and mode is None and computer is None:
self.__key = _winreg.OpenKey(key.__key, '')
elif isinstance(key, (int, _winreg.HKEYType)) and isinstance(subkey, str) and mode is None and computer is None:
self.__key = _winreg.OpenKey(key, subkey)
elif isinstance(key, Key) and isinstance(subkey, str) and mode is None and computer is None:
self.__key = _winreg.OpenKey(key.__key, subkey)
elif isinstance(key, (int, _winreg.HKEYType)) and subkey is None and isinstance(mode, int) and computer is None:
self.__key = _winreg.OpenKey(key, '', 0, mode)
elif isinstance(key, Key) and subkey is None and isinstance(mode, int) and computer is None:
self.__key = _winreg.OpenKey(key.__key, '', 0, mode)
elif isinstance(key, (int, _winreg.HKEYType)) and isinstance(subkey, str) and isinstance(mode, int) and computer is None:
self.__key = _winreg.OpenKey(key, subkey, 0, mode)
elif isinstance(key, Key) and isinstance(subkey, str) and isinstance(mode, int) and computer is None:
self.__key = _winreg.OpenKey(key.__key, subkey, 0, mode)
elif isinstance(key, int) and subkey is None and mode is None and isinstance(computer, str):
self.__key = _winreg.ConnectRegistry(computer, key)
elif isinstance(key, int) and isinstance(subkey, str) and mode is None and isinstance(computer, str):
self.__key = _winreg.OpenKey(_winreg.ConnectRegistry(computer, key), subkey)
elif isinstance(key, int) and subkey is None and isinstance(mode, int) and isinstance(computer, str):
self.__key = _winreg.OpenKey(_winreg.ConnectRegistry(computer, key), '', 0, mode)
elif isinstance(key, int) and isinstance(subkey, str) and isinstance(mode, int) and isinstance(computer, str):
self.__key = _winreg.OpenKey(_winreg.ConnectRegistry(computer, key), subkey, 0, mode)
else:
raise TypeError, 'Please check documentation.'
self.__keys = Keys(self.__key)
self.__values = Values(self.__key)
self.__repr = 'Key(%s)' % ', '.join([repr(key)] + ['%s=%r' % (key, value) for key, value in zip(('subkey', 'mode', 'computer'), (subkey, mode, computer)) if value is not None])
def read_subkeys(self, regKey):
self._log("Reading subkeys for registry key: %s" % regKey)
registryHandles = []
subkeys = []
path = regKey.split("/")
hiveName = path.pop(0)
hive = reg.ConnectRegistry(None, self.regKeys[hiveName][0])
registryHandle = reg.OpenKey(hive, self.regKeys[hiveName][1])
registryHandles.append(hive)
self._log("Connected to registry at location: %s" % hiveName)
for step in path:
registryHandles.append(registryHandle)
registryHandle = reg.OpenKey(registryHandle, step)
i = 0
while True:
try:
subkey = reg.EnumKey(registryHandle, i)
self._log("Found subkey: %s" % subkey)
subkeys.append(subkey)
i += 1
except EnvironmentError:
break
self._log("Found %d subkeys." % len(subkeys))
self._log("Closing %d registry handles..." % len(registryHandles))
for handle in registryHandles:
reg.CloseKey(handle)
self._log("Done. Subkey enumeration completed.")
return subkeys
def remove_certificate(self, certificate):
CONTAINS_SUBKEYS = 0
registryHandles = []
returnValue = False
path = certificate["RegPath"].split("/")
hiveName = path.pop(0)
keyName = path.pop(-1)
hive = reg.ConnectRegistry(None, self.regKeys[hiveName][0])
registryHandle = reg.OpenKey(hive, self.regKeys[hiveName][1])
self._log("Connected to registry at location: %s" % hiveName)
for step in path:
registryHandles.append(registryHandle)
registryHandle = reg.OpenKey(registryHandle, step)
try:
deletionCandidate = reg.OpenKey(registryHandle, keyName)
self._log("Querying deletion canditate: %s" % certificate["RegPath"])
if not reg.QueryInfoKey(deletionCandidate)[CONTAINS_SUBKEYS]:
self._log("Attempting to delete key: %s" % certificate["RegPath"])
reg.CloseKey(deletionCandidate)
reg.DeleteKey(registryHandle, keyName)
self._log("Deleted key: %s" % certificate["RegPath"])
returnValue = True
else:
self._error_log("Unable to delete key: %s. Key contains subkeys." % certificate["RegPath"])
registryHandles.append(deletionCandidate)
raise WindowsError
except WindowsError as e:
self._error_log("Unable to delete key: %s. Windows error." % certificate["RegPath"])
self._error_log("%s: %s" % (certificate["RegPath"], str(e)))
pass
self._log("Closing registry handles...")
for handle in registryHandles:
reg.CloseKey(handle)
reg.CloseKey(hive)
self._log("Registry handles closed.")
return returnValue
def _get_awvs_console_path(self):
"""Return
"""
try:
conn = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
wvs_path = _winreg.QueryValue(conn, 'SOFTWARE\Classes\Acunetix_WVS_Scan\Shell\Open\Command')
_winreg.CloseKey(conn)
wvs_path = re.search('"([^"]*)"', wvs_path).group(1)
wvs_dir = os.path.dirname(wvs_path)
return os.path.join(wvs_dir, 'wvs_console.exe')
except Exception, e:
LOG.error(e, exc_info=True)
def _settzkeyname():
global TZKEYNAME
handle = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
try:
_winreg.OpenKey(handle, TZKEYNAMENT).Close()
TZKEYNAME = TZKEYNAMENT
except WindowsError:
TZKEYNAME = TZKEYNAME9X
handle.Close()
def list():
"""Return a list of all time zones known to the system."""
handle = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
tzkey = _winreg.OpenKey(handle, TZKEYNAME)
result = [_winreg.EnumKey(tzkey, i)
for i in range(_winreg.QueryInfoKey(tzkey)[0])]
tzkey.Close()
handle.Close()
return result
def __init__(self, name):
self._name = name
handle = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
tzkey = _winreg.OpenKey(handle, "%s\%s" % (TZKEYNAME, name))
keydict = valuestodict(tzkey)
tzkey.Close()
handle.Close()
self._stdname = keydict["Std"].encode("iso-8859-1")
self._dstname = keydict["Dlt"].encode("iso-8859-1")
self._display = keydict["Display"]
# See http://ww_winreg.jsiinc.com/SUBA/tip0300/rh0398.htm
tup = struct.unpack("=3l16h", keydict["TZI"])
self._stdoffset = -tup[0]-tup[1] # Bias + StandardBias * -1
self._dstoffset = self._stdoffset-tup[2] # + DaylightBias * -1
(self._stdmonth,
self._stddayofweek, # Sunday = 0
self._stdweeknumber, # Last = 5
self._stdhour,
self._stdminute) = tup[4:9]
(self._dstmonth,
self._dstdayofweek, # Sunday = 0
self._dstweeknumber, # Last = 5
self._dsthour,
self._dstminute) = tup[12:17]
def __init__(self):
handle = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
tzlocalkey = _winreg.OpenKey(handle, TZLOCALKEYNAME)
keydict = valuestodict(tzlocalkey)
tzlocalkey.Close()
self._stdname = keydict["StandardName"].encode("iso-8859-1")
self._dstname = keydict["DaylightName"].encode("iso-8859-1")
try:
tzkey = _winreg.OpenKey(handle, "%s\%s"%(TZKEYNAME, self._stdname))
_keydict = valuestodict(tzkey)
self._display = _keydict["Display"]
tzkey.Close()
except OSError:
self._display = None
handle.Close()
self._stdoffset = -keydict["Bias"]-keydict["StandardBias"]
self._dstoffset = self._stdoffset-keydict["DaylightBias"]
# See http://ww_winreg.jsiinc.com/SUBA/tip0300/rh0398.htm
tup = struct.unpack("=8h", keydict["StandardStart"])
(self._stdmonth,
self._stddayofweek, # Sunday = 0
self._stdweeknumber, # Last = 5
self._stdhour,
self._stdminute) = tup[1:6]
tup = struct.unpack("=8h", keydict["DaylightStart"])
(self._dstmonth,
self._dstdayofweek, # Sunday = 0
self._dstweeknumber, # Last = 5
self._dsthour,
self._dstminute) = tup[1:6]
def get_localzone_name():
# Windows is special. It has unique time zone names (in several
# meanings of the word) available, but unfortunately, they can be
# translated to the language of the operating system, so we need to
# do a backwards lookup, by going through all time zones and see which
# one matches.
handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
TZLOCALKEYNAME = r'SYSTEM\CurrentControlSet\Control\TimeZoneInformation'
localtz = winreg.OpenKey(handle, TZLOCALKEYNAME)
keyvalues = valuestodict(localtz)
localtz.Close()
if 'TimeZoneKeyName' in keyvalues:
# Windows 7 (and Vista?)
# For some reason this returns a string with loads of NUL bytes at
# least on some systems. I don't know if this is a bug somewhere, I
# just work around it.
tzkeyname = keyvalues['TimeZoneKeyName'].split('\x00', 1)[0]
else:
# Windows 2000 or XP
# This is the localized name:
tzwin = keyvalues['StandardName']
# Open the list of timezones to look up the real name:
TZKEYNAME = r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones'
tzkey = winreg.OpenKey(handle, TZKEYNAME)
# Now, match this value to Time Zone information
tzkeyname = None
for i in range(winreg.QueryInfoKey(tzkey)[0]):
subkey = winreg.EnumKey(tzkey, i)
sub = winreg.OpenKey(tzkey, subkey)
data = valuestodict(sub)
sub.Close()
if data['Std'] == tzwin:
tzkeyname = subkey
break
tzkey.Close()
handle.Close()
if tzkeyname is None:
raise LookupError('Can not find Windows timezone configuration')
timezone = tz_names.get(tzkeyname)
if timezone is None:
# Nope, that didn't work. Try adding 'Standard Time',
# it seems to work a lot of times:
timezone = tz_names.get(tzkeyname + ' Standard Time')
# Return what we have.
if timezone is None:
raise pytz.UnknownTimeZoneError('Can not find timezone ' + tzkeyname)
return timezone
def read_registry(self):
"""Extract resolver configuration from the Windows registry."""
lm = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
want_scan = False
try:
try:
# XP, 2000
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters')
want_scan = True
except EnvironmentError:
# ME
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\VxD\MSTCP')
try:
self._config_win32_fromkey(tcp_params)
finally:
tcp_params.Close()
if want_scan:
interfaces = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters'
r'\Interfaces')
try:
i = 0
while True:
try:
guid = _winreg.EnumKey(interfaces, i)
i += 1
key = _winreg.OpenKey(interfaces, guid)
if not self._win32_is_nic_enabled(lm, guid, key):
continue
try:
self._config_win32_fromkey(key)
finally:
key.Close()
except EnvironmentError:
break
finally:
interfaces.Close()
finally:
lm.Close()
def read_registry(self):
"""Extract resolver configuration from the Windows registry."""
lm = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
want_scan = False
try:
try:
# XP, 2000
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters')
want_scan = True
except EnvironmentError:
# ME
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\VxD\MSTCP')
try:
self._config_win32_fromkey(tcp_params)
finally:
tcp_params.Close()
if want_scan:
interfaces = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters'
r'\Interfaces')
try:
i = 0
while True:
try:
guid = _winreg.EnumKey(interfaces, i)
i += 1
key = _winreg.OpenKey(interfaces, guid)
if not self._win32_is_nic_enabled(lm, guid, key):
continue
try:
self._config_win32_fromkey(key)
finally:
key.Close()
except EnvironmentError:
break
finally:
interfaces.Close()
finally:
lm.Close()
def read_registry(self):
"""Extract resolver configuration from the Windows registry."""
lm = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
want_scan = False
try:
try:
# XP, 2000
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters')
want_scan = True
except EnvironmentError:
# ME
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\VxD\MSTCP')
try:
self._config_win32_fromkey(tcp_params)
finally:
tcp_params.Close()
if want_scan:
interfaces = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters'
r'\Interfaces')
try:
i = 0
while True:
try:
guid = _winreg.EnumKey(interfaces, i)
i += 1
key = _winreg.OpenKey(interfaces, guid)
if not self._win32_is_nic_enabled(lm, guid, key):
continue
try:
self._config_win32_fromkey(key)
finally:
key.Close()
except EnvironmentError:
break
finally:
interfaces.Close()
finally:
lm.Close()
def read_registry(self):
"""Extract resolver configuration from the Windows registry."""
lm = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
want_scan = False
try:
try:
# XP, 2000
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters')
want_scan = True
except EnvironmentError:
# ME
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\VxD\MSTCP')
try:
self._config_win32_fromkey(tcp_params)
finally:
tcp_params.Close()
if want_scan:
interfaces = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters'
r'\Interfaces')
try:
i = 0
while True:
try:
guid = _winreg.EnumKey(interfaces, i)
i += 1
key = _winreg.OpenKey(interfaces, guid)
if not self._win32_is_nic_enabled(lm, guid, key):
continue
try:
self._config_win32_fromkey(key)
finally:
key.Close()
except EnvironmentError:
break
finally:
interfaces.Close()
finally:
lm.Close()
def read_registry(self):
"""Extract resolver configuration from the Windows registry."""
lm = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
want_scan = False
try:
try:
# XP, 2000
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters')
want_scan = True
except EnvironmentError:
# ME
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\VxD\MSTCP')
try:
self._config_win32_fromkey(tcp_params)
finally:
tcp_params.Close()
if want_scan:
interfaces = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters'
r'\Interfaces')
try:
i = 0
while True:
try:
guid = _winreg.EnumKey(interfaces, i)
i += 1
key = _winreg.OpenKey(interfaces, guid)
if not self._win32_is_nic_enabled(lm, guid, key):
continue
try:
self._config_win32_fromkey(key)
finally:
key.Close()
except EnvironmentError:
break
finally:
interfaces.Close()
finally:
lm.Close()
def get_local_data():
tmp_list = []
out_list = []
global g_verbose
try:
import _winreg as reg
except ImportError:
print "[-] \'winreg.py\' not found... Is this a Windows system?"
sys.exit(1)
hReg = reg.ConnectRegistry(None, reg.HKEY_LOCAL_MACHINE)
hSystem = reg.OpenKey(hReg, r'SYSTEM')
for i in xrange(1024):
try:
control_name = reg.EnumKey(hSystem, i)
if 'controlset' in control_name.lower():
hSessionMan = reg.OpenKey(hReg,
'SYSTEM\\%s\\Control\\Session Manager' % control_name)
for i in xrange(1024):
try:
subkey_name = reg.EnumKey(hSessionMan, i)
if ('appcompatibility' in subkey_name.lower()
or 'appcompatcache' in subkey_name.lower()):
appcompat_key = reg.OpenKey(hSessionMan, subkey_name)
bin_data = reg.QueryValueEx(appcompat_key,
'AppCompatCache')[0]
tmp_list = read_cache(bin_data)
if tmp_list:
path_name = 'SYSTEM\\%s\\Control\\Session Manager\\%s' % (control_name, subkey_name)
for row in tmp_list:
if g_verbose:
row.append(path_name)
if row not in out_list:
out_list.append(row)
except EnvironmentError:
break
except EnvironmentError:
break
if len(out_list) == 0:
return None
else:
#Add the header and return the list.
if g_verbose:
out_list.insert(0, output_header + ['Key Path'])
return out_list
else:
#Only return unique entries.
out_list = unique_list(out_list)
out_list.insert(0, output_header)
return out_list
# Read a MIR XML zip archive.
def get_localzone_name():
# Windows is special. It has unique time zone names (in several
# meanings of the word) available, but unfortunately, they can be
# translated to the language of the operating system, so we need to
# do a backwards lookup, by going through all time zones and see which
# one matches.
handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
TZLOCALKEYNAME = r'SYSTEM\CurrentControlSet\Control\TimeZoneInformation'
localtz = winreg.OpenKey(handle, TZLOCALKEYNAME)
keyvalues = valuestodict(localtz)
localtz.Close()
if 'TimeZoneKeyName' in keyvalues:
# Windows 7 (and Vista?)
# For some reason this returns a string with loads of NUL bytes at
# least on some systems. I don't know if this is a bug somewhere, I
# just work around it.
tzkeyname = keyvalues['TimeZoneKeyName'].split('\x00', 1)[0]
else:
# Windows 2000 or XP
# This is the localized name:
tzwin = keyvalues['StandardName']
# Open the list of timezones to look up the real name:
TZKEYNAME = r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones'
tzkey = winreg.OpenKey(handle, TZKEYNAME)
# Now, match this value to Time Zone information
tzkeyname = None
for i in range(winreg.QueryInfoKey(tzkey)[0]):
subkey = winreg.EnumKey(tzkey, i)
sub = winreg.OpenKey(tzkey, subkey)
data = valuestodict(sub)
sub.Close()
if data['Std'] == tzwin:
tzkeyname = subkey
break
tzkey.Close()
handle.Close()
if tzkeyname is None:
raise LookupError('Can not find Windows timezone configuration')
timezone = tz_names.get(tzkeyname)
if timezone is None:
# Nope, that didn't work. Try adding 'Standard Time',
# it seems to work a lot of times:
timezone = tz_names.get(tzkeyname + ' Standard Time')
# Return what we have.
if timezone is None:
raise pytz.UnknownTimeZoneError('Can not find timezone ' + tzkeyname)
return timezone
def read_registry(self):
"""Extract resolver configuration from the Windows registry."""
lm = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
want_scan = False
try:
try:
# XP, 2000
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters')
want_scan = True
except EnvironmentError:
# ME
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\VxD\MSTCP')
try:
self._config_win32_fromkey(tcp_params)
finally:
tcp_params.Close()
if want_scan:
interfaces = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters'
r'\Interfaces')
try:
i = 0
while True:
try:
guid = _winreg.EnumKey(interfaces, i)
i += 1
key = _winreg.OpenKey(interfaces, guid)
if not self._win32_is_nic_enabled(lm, guid, key):
continue
try:
self._config_win32_fromkey(key)
finally:
key.Close()
except EnvironmentError:
break
finally:
interfaces.Close()
finally:
lm.Close()
def read_registry(self):
"""Extract resolver configuration from the Windows registry."""
lm = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
want_scan = False
try:
try:
# XP, 2000
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters')
want_scan = True
except EnvironmentError:
# ME
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\VxD\MSTCP')
try:
self._config_win32_fromkey(tcp_params)
finally:
tcp_params.Close()
if want_scan:
interfaces = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters'
r'\Interfaces')
try:
i = 0
while True:
try:
guid = _winreg.EnumKey(interfaces, i)
i += 1
key = _winreg.OpenKey(interfaces, guid)
if not self._win32_is_nic_enabled(lm, guid, key):
continue
try:
self._config_win32_fromkey(key)
finally:
key.Close()
except EnvironmentError:
break
finally:
interfaces.Close()
finally:
lm.Close()
def set_mac_address(new_mac):
"""
set the device's MAC address
"""
# Locate adapter's registry and update network address (mac)
reg_hdl = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
key = winreg.OpenKey(reg_hdl, WIN_REGISTRY_PATH)
info = winreg.QueryInfoKey(key)
# Find adapter key based on sub keys
adapter_key = None
adapter_path = None
target_index = -1
for index in range(info[0]):
subkey = winreg.EnumKey(key, index)
path = WIN_REGISTRY_PATH + "\\" + subkey
if subkey == 'Properties':
break
# Check for adapter match for appropriate interface
new_key = winreg.OpenKey(reg_hdl, path)
try:
adapterDesc = winreg.QueryValueEx(new_key, "DriverDesc")
if adapterDesc[0] == target_device:
adapter_path = path
target_index = index
break
else:
winreg.CloseKey(new_key)
except (WindowsError) as err:
if err.errno == 2: # register value not found, ok to ignore
pass
else:
raise err
if adapter_path is None:
print 'Device not found.'
winreg.CloseKey(key)
winreg.CloseKey(reg_hdl)
return
# Registry path found update mac addr
adapter_key = winreg.OpenKey(reg_hdl, adapter_path, 0, winreg.KEY_WRITE)
winreg.SetValueEx(adapter_key, "NetworkAddress", 0, winreg.REG_SZ, new_mac)
winreg.CloseKey(adapter_key)
winreg.CloseKey(key)
winreg.CloseKey(reg_hdl)
# Adapter must be restarted in order for change to take affect
# print 'Now you should restart your netsh'
restart_adapter(target_index)
# regex to MAC address like 00-00-00-00-00-00 or 00:00:00:00:00:00 or
# 000000000000
def read_registry(self):
"""Extract resolver configuration from the Windows registry."""
lm = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
want_scan = False
try:
try:
# XP, 2000
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters')
want_scan = True
except EnvironmentError:
# ME
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\VxD\MSTCP')
try:
self._config_win32_fromkey(tcp_params)
finally:
tcp_params.Close()
if want_scan:
interfaces = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters'
r'\Interfaces')
try:
i = 0
while True:
try:
guid = _winreg.EnumKey(interfaces, i)
i += 1
key = _winreg.OpenKey(interfaces, guid)
if not self._win32_is_nic_enabled(lm, guid, key):
continue
try:
self._config_win32_fromkey(key)
finally:
key.Close()
except EnvironmentError:
break
finally:
interfaces.Close()
finally:
lm.Close()
def read_registry(self):
"""Extract resolver configuration from the Windows registry."""
lm = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
want_scan = False
try:
try:
# XP, 2000
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters')
want_scan = True
except EnvironmentError:
# ME
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\VxD\MSTCP')
try:
self._config_win32_fromkey(tcp_params)
finally:
tcp_params.Close()
if want_scan:
interfaces = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters'
r'\Interfaces')
try:
i = 0
while True:
try:
guid = _winreg.EnumKey(interfaces, i)
i += 1
key = _winreg.OpenKey(interfaces, guid)
if not self._win32_is_nic_enabled(lm, guid, key):
continue
try:
self._config_win32_fromkey(key)
finally:
key.Close()
except EnvironmentError:
break
finally:
interfaces.Close()
finally:
lm.Close()
def read_registry(self):
"""Extract resolver configuration from the Windows registry."""
lm = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
want_scan = False
try:
try:
# XP, 2000
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters')
want_scan = True
except EnvironmentError:
# ME
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\VxD\MSTCP')
try:
self._config_win32_fromkey(tcp_params)
finally:
tcp_params.Close()
if want_scan:
interfaces = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters'
r'\Interfaces')
try:
i = 0
while True:
try:
guid = _winreg.EnumKey(interfaces, i)
i += 1
key = _winreg.OpenKey(interfaces, guid)
if not self._win32_is_nic_enabled(lm, guid, key):
continue
try:
self._config_win32_fromkey(key)
finally:
key.Close()
except EnvironmentError:
break
finally:
interfaces.Close()
finally:
lm.Close()
def get_localzone_name():
# Windows is special. It has unique time zone names (in several
# meanings of the word) available, but unfortunately, they can be
# translated to the language of the operating system, so we need to
# do a backwards lookup, by going through all time zones and see which
# one matches.
handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
TZLOCALKEYNAME = r'SYSTEM\CurrentControlSet\Control\TimeZoneInformation'
localtz = winreg.OpenKey(handle, TZLOCALKEYNAME)
keyvalues = valuestodict(localtz)
localtz.Close()
if 'TimeZoneKeyName' in keyvalues:
# Windows 7 (and Vista?)
# For some reason this returns a string with loads of NUL bytes at
# least on some systems. I don't know if this is a bug somewhere, I
# just work around it.
tzkeyname = keyvalues['TimeZoneKeyName'].split('\x00', 1)[0]
else:
# Windows 2000 or XP
# This is the localized name:
tzwin = keyvalues['StandardName']
# Open the list of timezones to look up the real name:
TZKEYNAME = r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones'
tzkey = winreg.OpenKey(handle, TZKEYNAME)
# Now, match this value to Time Zone information
tzkeyname = None
for i in range(winreg.QueryInfoKey(tzkey)[0]):
subkey = winreg.EnumKey(tzkey, i)
sub = winreg.OpenKey(tzkey, subkey)
data = valuestodict(sub)
sub.Close()
if data['Std'] == tzwin:
tzkeyname = subkey
break
tzkey.Close()
handle.Close()
if tzkeyname is None:
raise LookupError('Can not find Windows timezone configuration')
timezone = tz_names.get(tzkeyname)
if timezone is None:
# Nope, that didn't work. Try adding 'Standard Time',
# it seems to work a lot of times:
timezone = tz_names.get(tzkeyname + ' Standard Time')
# Return what we have.
if timezone is None:
raise pytz.UnknownTimeZoneError('Can not find timezone ' + tzkeyname)
return timezone
def read_registry(self):
"""Extract resolver configuration from the Windows registry."""
lm = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
want_scan = False
try:
try:
# XP, 2000
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters')
want_scan = True
except EnvironmentError:
# ME
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\VxD\MSTCP')
try:
self._config_win32_fromkey(tcp_params)
finally:
tcp_params.Close()
if want_scan:
interfaces = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters'
r'\Interfaces')
try:
i = 0
while True:
try:
guid = _winreg.EnumKey(interfaces, i)
i += 1
key = _winreg.OpenKey(interfaces, guid)
if not self._win32_is_nic_enabled(lm, guid, key):
continue
try:
self._config_win32_fromkey(key)
finally:
key.Close()
except EnvironmentError:
break
finally:
interfaces.Close()
finally:
lm.Close()
def read_registry(self):
"""Extract resolver configuration from the Windows registry."""
lm = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
want_scan = False
try:
try:
# XP, 2000
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters')
want_scan = True
except EnvironmentError:
# ME
tcp_params = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\VxD\MSTCP')
try:
self._config_win32_fromkey(tcp_params)
finally:
tcp_params.Close()
if want_scan:
interfaces = _winreg.OpenKey(lm,
r'SYSTEM\CurrentControlSet'
r'\Services\Tcpip\Parameters'
r'\Interfaces')
try:
i = 0
while True:
try:
guid = _winreg.EnumKey(interfaces, i)
i += 1
key = _winreg.OpenKey(interfaces, guid)
if not self._win32_is_nic_enabled(lm, guid, key):
continue
try:
self._config_win32_fromkey(key)
finally:
key.Close()
except EnvironmentError:
break
finally:
interfaces.Close()
finally:
lm.Close()
def get_localzone_name():
# Windows is special. It has unique time zone names (in several
# meanings of the word) available, but unfortunately, they can be
# translated to the language of the operating system, so we need to
# do a backwards lookup, by going through all time zones and see which
# one matches.
handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
TZLOCALKEYNAME = r'SYSTEM\CurrentControlSet\Control\TimeZoneInformation'
localtz = winreg.OpenKey(handle, TZLOCALKEYNAME)
keyvalues = valuestodict(localtz)
localtz.Close()
if 'TimeZoneKeyName' in keyvalues:
# Windows 7 (and Vista?)
# For some reason this returns a string with loads of NUL bytes at
# least on some systems. I don't know if this is a bug somewhere, I
# just work around it.
tzkeyname = keyvalues['TimeZoneKeyName'].split('\x00', 1)[0]
else:
# Windows 2000 or XP
# This is the localized name:
tzwin = keyvalues['StandardName']
# Open the list of timezones to look up the real name:
TZKEYNAME = r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones'
tzkey = winreg.OpenKey(handle, TZKEYNAME)
# Now, match this value to Time Zone information
tzkeyname = None
for i in range(winreg.QueryInfoKey(tzkey)[0]):
subkey = winreg.EnumKey(tzkey, i)
sub = winreg.OpenKey(tzkey, subkey)
data = valuestodict(sub)
sub.Close()
if data['Std'] == tzwin:
tzkeyname = subkey
break
tzkey.Close()
handle.Close()
if tzkeyname is None:
raise LookupError('Can not find Windows timezone configuration')
timezone = tz_names.get(tzkeyname)
if timezone is None:
# Nope, that didn't work. Try adding 'Standard Time',
# it seems to work a lot of times:
timezone = tz_names.get(tzkeyname + ' Standard Time')
# Return what we have.
if timezone is None:
raise pytz.UnknownTimeZoneError('Can not find timezone ' + tzkeyname)
return timezone