开发者

python script to find Installed programs in Uninstall folder in registry

开发者 https://www.devze.com 2023-02-16 22:36 出处:网络
I am working on creating a python script to find Installed programs in Uninstall folder in registry, the script works perfectly fine on 32 bit machines but errors out with a wmi error on 64 bit machin

I am working on creating a python script to find Installed programs in Uninstall folder in registry, the script works perfectly fine on 32 bit machines but errors out with a wmi error on 64 bit machines. Am not able to get hold of a wmi module for python on 64 bit machines.Is there one at all? Please ignore indentation errors. I found this script in some forum, apologies for not giving due credit to the corresponding author

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')
           开发者_如何学Python     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)


try using _winreg instead of wmi, and I believe there's a slightly different registry tree for 64-bit that keeps 32 and 64 bit apps separate, so you may need to enumerate 2 registry trees.


This might not be the best code out there implemented using this but it works for my application. I hope you can use it or improve it.

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))

Example result is the following:

[   [['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'

The results ensure that there is always a display name. This was quite challenging to solve given I'm new to Python. But anyway, it uses the last key address for Display name if a certain application has no Display Name in the Values list.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号