python脚本在注册表中的Uninstall文件夹中查找已安装的程序

时间:2011-03-14 16:51:10

标签: python wmi

我正在创建一个python脚本,用于在注册表中的Uninstall文件夹中查找已安装的程序,该脚本在32位计算机上运行良好,但在64位计算机上出现wmi错误。 我无法在64位计算机上获得用于python的wmi模块。那里有一个吗? 请忽略缩进错误。 我在某个论坛中发现了这个脚本,对于没有给予相应作者的应有的信任而道歉

r = wmi.Registry()
result, names = r.EnumKey (hDefKey=HKEY_LOCAL_MACHINE, sSubKeyName=r"Software\Microsoft\Windows\CurrentVersion\Uninstall")

    separator = "*" * 80
    keyPath = r"Software\Microsoft\Windows\CurrentVersion\Uninstall"
    for subkey in names:
       try:

            path = keyPath + "\\" + subkey
            key = OpenKey(HKEY_LOCAL_MACHINE, path, 0, KEY_ALL_ACCESS)

            try:
                temp = QueryValueEx(key, 'DisplayName')
                temp1 = QueryValueEx(key, 'DisplayVersion')
                temp2 = QueryValueEx(key, 'Publisher')
                display = str(temp[0])
                display_ver=str(temp1[0])
                display_p=str(temp2[0])

                print ('Display Name: ' + display + '\nDisplay version:  ' + display_ver + '\nVendor/Publisher:  ' + display_p +'\nRegkey: ' + subkey + '\n')

            except:
                print ('Regkey: ' + subkey + '\n')


        except:
            fp = StringIO.StringIO()
            traceback.print_exc(file=fp)
            errorMessage = fp.getvalue()
            #error = 'Error for ' + key + '. Message follows:\n' + errorMessage
            #HelperFuncs.LogError(error)

2 个答案:

答案 0 :(得分:0)

尝试使用_winreg而不是wmi,我相信64位的注册表树略有不同,使32位和64位应用程序分开,因此您可能需要枚举2个注册表树。

答案 1 :(得分:0)

这可能不是使用this实现的最佳代码,但它适用于我的应用程序。我希望你能用它或改进它。

import wmi
import pprint # not really necessary. Only used to pretty print results. :D

class RegistryApplications:
    """Provides WMI based accessors to the computer/remote computers list of Applications installed. The data is taken
    from the registry where uninstall paths are kept.

    Keyword arguments:
    real -- the real part (default 0.0)
    imag -- the imaginary part (default 0.0)
    """

    HKEY_CLASSES_ROOT = 2147483648
    HKEY_CURRENT_USER = 2147483649
    HKEY_LOCAL_MACHINE = 2147483650
    HKEY_USERS = 2147483651
    HKEY_CURRENT_CONFIG = 2147483653

    REG_SZ = 1
    REG_EXPAND_SZ = (2)
    REG_BINARY = (3)
    REG_DWORD = (4)
    REG_MULTI_SZ = (7)
    REG_QWORD = (11)

    strComputer = r"myremotepcname"
    strUsername = r"myusername"
    strPassword = r"mypassword"

    intTotalNumberOfInstalledApps = 0

    strApplications = []
    __singleApplicationData = []

    def __init__(self, computerName=r".", userName=r"myusername", password=r"mypassword"):
        """
        Keyword arguments:
        computerName -- name of the computer to access. (default=".")
        userName -- username of the computer preferably Admin member. (default="myusername")
        password -- password string of the username for that particular computer. (default="mypassword")
        """
        assert isinstance(userName, str)
        assert isinstance(password, str)
        assert isinstance(computerName, str)
        self.strComputer = computerName
        self.strUsername = userName
        self.strPassword = password

    def setSecurity(self, userName, password):
        """
        Keyword arguments:
        userName -- username of the computer preferably Admin member. (default="myusername")
        password -- password string of the username for that particular computer. (default="mypassword")
        """
        assert isinstance(userName, str)
        assert isinstance(password, str)
        self.strUsername = userName
        self.strPassword = password

    def setComputerName(self, computerName):
        """
        Keyword arguments:
        computerName -- name of the computer to access. (default=".")
        """
        assert isinstance(computerName, str)
        self.strComputer = computerName

    @property
    def getResult(self):
        """Description: Initiates the collection of data from the remote or local computer. The result is returned.
        Immediately by this function.
        """
        oReg = wmi.WMI(
            moniker=r"winmgmts:{impersonationLevel=impersonate}!\\" + self.strComputer + r"\root\default:StdRegProv",
            user=self.strUsername,
            password=self.strPassword,
            computer=self.strComputer,
        )
        sSubKeyName = r"Software\Microsoft\Windows\CurrentVersion\Uninstall"

        result, keys = oReg.EnumKey(
            hDefKey=self.HKEY_LOCAL_MACHINE,
            sSubKeyName=sSubKeyName,
        )

        sPossibleValues = []
        listResult = []

        if result == 0:

            self.intTotalNumberOfInstalledApps = len(keys)

            # Each key is a single application.
            for key in keys:
                self.__singleApplicationData = []

                # print key
                path = sSubKeyName + '\\' + key
                subResult, sNames, sIntType = oReg.EnumValues(
                    hDefKey=self.HKEY_LOCAL_MACHINE,
                    sSubKeyName=path,
                )

                if "DisplayName" not in sNames:
                    self.__singleApplicationData.append(["DisplayName", key])
                for x in xrange(0, len(sNames)):
                    if sIntType[x] == self.REG_SZ or sIntType[x] == self.REG_EXPAND_SZ or sIntType[x] == self.REG_MULTI_SZ:
                        if [sNames[x], sIntType[x]] not in sPossibleValues:
                            sPossibleValues.append([sNames[x], sIntType[x]])

                        subResult, strValueName = oReg.GetStringValue(
                            hDefKey=self.HKEY_LOCAL_MACHINE,
                            sSubKeyName=sSubKeyName + '\\' + key,
                            sValueName=sNames[x],
                        )

                        # Only insert to result if the value & name is of len > 0
                        if subResult == 0 and ((len(sNames[x]) > 0 and len(strValueName) > 0) or (sNames[x] == "DisplayName")):
                            self.__singleApplicationData.append([sNames[x], strValueName])

                if (len(self.__singleApplicationData) > 0):
                    listResult.append(self.__singleApplicationData)

        return listResult

# Example usage
x = RegistryApplications(
    computerName='myremotepcname',
    # computerName='.', # use this (".") for localhost
    userName='myusername',
    password='mypassword'
)

result = x.getResult
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(result)
pp.pprint("Total Number of Installed Applications via Result: " + str(len(result)))
pp.pprint("Total Number of Installed Applications via Keys: " + str(x.intTotalNumberOfInstalledApps))

示例结果如下:

[   [['DisplayName', u'AddressBook']],
    [['DisplayName', u'Connection Manager']],
    [['DisplayName', u'DirectDrawEx']],
    [['DisplayName', u'DXM_Runtime']],
    [['DisplayName', u'Fontcore']],
    [['DisplayName', u'IE40']],
    [['DisplayName', u'IE4Data']],
    [['DisplayName', u'IE5BAKEX']],
    [['DisplayName', u'IEData']],
    [['DisplayName', u'MobileOptionPack']],
    [['DisplayName', u'MPlayer2']],
    [['DisplayName', u'SchedulingAgent']],
    [   [u'DisplayName', u'STAF'],
        [   u'UninstallString',
            u'"C:\\STAF\\Uninstall_STAF\\Uninstall_STAF.exe"'],
        [u'Publisher', u'IBM'],
        [u'URLUpdateInfo', u'http://staf.sourceforge.net'],
        [u'ProductID', u'78fbc320-1ee9-11b2-bfbf-f3a634900050'],
        [u'InstallLocation', u'C:\\STAF'],
        [u'InstallDate', u'Wed Oct 22 10:45:02 CST 2014'],
        [u'HelpLink', u'http://staf.sourceforge.net'],
        [u'DisplayVersion', u'3.4.19.0']],
    [['DisplayName', u'WIC']],
    [   [u'DisplayVersion', u'11.0.61030'],
        [u'HelpLink', u'http://go.microsoft.com/fwlink/?LinkId=133405'],
        [u'InstallDate', u'20141028'],
        [   u'InstallSource',
            u'C:\\ProgramData\\Package Cache\\{23BC2D90-1227-3F95-B943-3089224C9973}v11.0.61030\\'],
        [u'Publisher', u'Microsoft Corporation'],
        [u'DisplayName', u'Microsoft Visual Studio 2012 Performance Tools']],
    [   [u'DisplayVersion', u'11.0.61030'],
        [u'InstallDate', u'20141028'],
        [   u'InstallSource',
            u'C:\\ProgramData\\Package Cache\\{615895AB-34F5-3357-88A2-B37215E601C5}v11.0.61030\\'],
        [u'Publisher', u'Microsoft Corporation'],
        [u'DisplayName', u'Microsoft Visual Studio 2012 Lab Agent  Core']],
    [   [u'DisplayVersion', u'11.0.61030'],
        [u'InstallDate', u'20141028'],
        [   u'InstallSource',
            u'C:\\ProgramData\\Package Cache\\{8877CE8C-7F87-4962-8BCF-DFAA2980D2CE}v11.0.61030\\packages\\IntelliTraceCore\\amd64\\'],
        [   u'ModifyPath',
            u'MsiExec.exe /I{8877CE8C-7F87-4962-8BCF-DFAA2980D2CE}'],
        [u'Publisher', u'Microsoft Corporation'],
        [   u'UninstallString',
            u'MsiExec.exe /I{8877CE8C-7F87-4962-8BCF-DFAA2980D2CE}'],
        [   u'DisplayName',
            u'Microsoft Visual Studio 2012 IntelliTrace Core amd64']],
    [   [u'DisplayVersion', u'11.0.61030'],
        [u'InstallDate', u'20141028'],
        [   u'InstallSource',
            u'C:\\ProgramData\\Package Cache\\{91EEBAED-0D80-344E-8DDA-64C35C1E0FB7}v11.0.61030\\packages\\LabAgentCoreresx64\\'],
        [u'Publisher', u'Microsoft Corporation'],
        [   u'DisplayName',
            u'Microsoft Visual Studio 2012 Lab Agent  CoreRes - ENU']],
    [   [u'DisplayVersion', u'11.0.61030'],
        [u'HelpLink', u'http://go.microsoft.com/fwlink/?LinkId=133405'],
        [u'InstallDate', u'20141028'],
        [   u'InstallSource',
            u'C:\\ProgramData\\Package Cache\\{B39D25FD-1403-3693-A428-8FE565B69708}v11.0.61030\\'],
        [u'Publisher', u'Microsoft Corporation'],
        [   u'DisplayName',
            u'Microsoft Visual Studio 2012 Performance Tools Language Pack - ENU']],
    [   [   u'Comments',
            u'Caution. Removing this product might prevent some applications from running.'],
        [u'DisplayVersion', u'11.0.61030'],
        [u'HelpLink', u'http://go.microsoft.com/fwlink/?LinkId=133405'],
        [u'InstallDate', u'20141028'],
        [   u'InstallSource',
            u'C:\\ProgramData\\Package Cache\\{CF2BEA3C-26EA-32F8-AA9B-331F7E34BA97}v11.0.61030\\packages\\vcRuntimeMinimum_amd64\\'],
        [   u'ModifyPath',
            u'MsiExec.exe /X{CF2BEA3C-26EA-32F8-AA9B-331F7E34BA97}'],
        [u'Publisher', u'Microsoft Corporation'],
        [   u'UninstallString',
            u'MsiExec.exe /X{CF2BEA3C-26EA-32F8-AA9B-331F7E34BA97}'],
        [   u'DisplayName',
            u'Microsoft Visual C++ 2012 x64 Minimum Runtime - 11.0.61030']]]
'Total Number of Installed Applications via Result: 20'
'Total Number of Installed Applications via Keys: 20'

结果确保始终显示名称。考虑到我是Python新手,解决这个问题非常困难。但无论如何,如果某个应用程序在“值”列表中没有“显示名称”,它会使用显示名称的最后一个键地址。