如何使用Python检索Registry值?

时间:2015-01-24 17:53:48

标签: python windows python-2.7 regedit

到目前为止,我已编写此代码;

from _winreg import *

def val2addr(val):
    addr = ''
    for ch in val:
        addr += '%02x '% ord(ch)
    addr = addr.strip(' ').replace(' ', ':')[0:17]
    return addr

def printNets():
    net = "SOFTWARE\Microsoft\Windows NT\CurrentVersion"+\
          "\NetworkList\Signatures\Unmanaged"
    key = OpenKey(HKEY_LOCAL_MACHINE, net)
    print '\n[*] Networks You Have Joined.'
    for i in range(100):
        try:
            guid = EnumKey(key, i)
            netKey = OpenKey(key, str(guid))
            (n, addr, t) = EnumValue(netKey, 5)
            (n, name, t) = EnumValue(netKey, 4)
            macAddr = val2addr(addr)
            netName = str(name)
            print '[+] ' + netName + ' ' + macAddr
            CloseKey(netKey)
        except:
            break
def main():
    printNets()
if __name__ == "_main_":
    main()

此脚本返回您已加入的所有WiFi网络的MAC地址和网络名称。

它从

返回值
  

计算机\ HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ Windows> NT \ CurrentVersion \ NetworkList \ Signatures \ Unmanaged \

我在Windows 8.1上并且已通过Regedit.exe检查以确保这是我正在检索的信息的正确位置。

当我运行此代码时,它说" WindowsError:[错误2]系统无法找到指定的文件"

那么我做错了什么呢?

P.S我在使用Python 2.7.9

完整追溯

追踪(最近一次呼叫最后一次):

File "<pyshell#11>", line 1, in <module>
    printNets()
  File "C:/Users/Nathaniel/Desktop/MacAddr Meta-Reader.py", line 13, in printNets
    key = OpenKey(HKEY_LOCAL_MACHINE, net)
WindowsError: [Error 2] The system cannot find the file specified

2 个答案:

答案 0 :(得分:3)

您可能在64位Windows上使用32位Python。在这种情况下,打开HKLM\SOFTWARE会被重定向到HKLM\SOFTWARE\Wow6432Node。如果需要64位密钥,则必须另外指定。例如:

key = OpenKey(HKEY_LOCAL_MACHINE, net, 0, 
              KEY_READ | KEY_WOW64_64KEY)

请注意,对于相对于此key对象打开的子键,指定KEY_WOW64_64KEY并非严格必要。


我将您的代码移植到Python 2和3中运行,添加了迭代器,并消除了硬编码的range和索引值。也许你会发现它有用:

from __future__ import print_function
import itertools

try:
    from winreg import *
except ImportError: # Python 2
    from _winreg import *

KEY_READ_64 = KEY_READ | KEY_WOW64_64KEY
ERROR_NO_MORE_ITEMS = 259

def iterkeys(key):
    for i in itertools.count():
        try:
            yield EnumKey(key, i)
        except OSError as e:
            if e.winerror == ERROR_NO_MORE_ITEMS:
                break
            raise

def itervalues(key):
    for i in itertools.count():
        try:
            yield EnumValue(key, i)
        except OSError as e:
            if e.winerror == ERROR_NO_MORE_ITEMS:
                break
            raise

def val2addr(val):
    return ':'.join('%02x' % b for b in bytearray(val))

NET_UNMANAGED = (r"SOFTWARE\Microsoft\Windows NT\CurrentVersion"
                 r"\NetworkList\Signatures\Unmanaged")

def printNets(keystr=NET_UNMANAGED):
    key = OpenKey(HKEY_LOCAL_MACHINE, keystr, 0, KEY_READ_64)
    print('\n[*] Networks You Have Joined.')
    for guid in iterkeys(key):
        netKey = OpenKey(key, guid)
        netName, macAddr = '', ''
        for name, data, rtype in itervalues(netKey):
            if name == 'FirstNetwork':
                netName = data
            elif name == 'DefaultGatewayMac':
                macAddr = val2addr(data)
        if netName:
            print('[+]', netName, macAddr)
        CloseKey(netKey)
    CloseKey(key)

密钥的安全描述符仅允许访问管理员和netprofm服务,如下所示。因此,您需要从提升的命令提示符运行脚本,或使用一种技术让脚本自动升级。

C:\>set NT=HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion    

C:\>accesschk -qldk "%NT%\NetworkList\Signatures\Unmanaged" 
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\
NetworkList\Signatures\Unmanaged
  DESCRIPTOR FLAGS:
      [SE_DACL_PRESENT]
      [SE_DACL_PROTECTED]
  OWNER: BUILTIN\Administrators
  [0] ACCESS_ALLOWED_ACE_TYPE: NT SERVICE\netprofm
          [CONTAINER_INHERIT_ACE]
          [INHERITED_ACE]
        KEY_QUERY_VALUE
        KEY_CREATE_LINK
        KEY_CREATE_SUB_KEY
        KEY_ENUMERATE_SUB_KEYS
        KEY_NOTIFY
        KEY_SET_VALUE
        READ_CONTROL
        DELETE
  [1] ACCESS_ALLOWED_ACE_TYPE: BUILTIN\Administrators
          [CONTAINER_INHERIT_ACE]
          [INHERITED_ACE]
        KEY_ALL_ACCESS

C:\>sc qdescription netprofm     
[SC] QueryServiceConfig2 SUCCESS

SERVICE_NAME: netprofm
DESCRIPTION:  Identifies the networks to which the computer has
connected, collects and stores properties for these networks, 
and notifies applications when these properties change.

答案 1 :(得分:0)

你有管理员权限吗?我试着用&#34; reg query&#34;确保我没有拼写问题,当我到达&#34; NetworkList&#34;我收到了Access拒绝错误。我改为管理员权限,一切都很好。

reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList
ERROR: Access is denied.