Esempio n. 1
0
def _get_typelib_info(keyid, version):
    """
    adapted from pywin32

    # Copyright (c) 1996-2008, Greg Stein and Mark Hammond.
    """

    import win32api
    import win32con

    collected = []
    help_path = ""
    key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT,
                              "TypeLib\\%s\\%s" % (keyid, version))
    try:
        num = 0
        while 1:
            try:
                sub_key = win32api.RegEnumKey(key, num)
            except win32api.error:
                break
            h_sub_key = win32api.RegOpenKey(key, sub_key)
            try:
                value, typ = win32api.RegQueryValueEx(h_sub_key, None)
                if typ == win32con.REG_EXPAND_SZ:
                    value = win32api.ExpandEnvironmentStrings(value)
            except win32api.error:
                value = ""
            if sub_key == "HELPDIR":
                help_path = value
            elif sub_key == "Flags":
                flags = value
            else:
                try:
                    lcid = int(sub_key)
                    lcidkey = win32api.RegOpenKey(key, sub_key)
                    # Enumerate the platforms
                    lcidnum = 0
                    while 1:
                        try:
                            platform = win32api.RegEnumKey(lcidkey, lcidnum)
                        except win32api.error:
                            break
                        try:
                            hplatform = win32api.RegOpenKey(lcidkey, platform)
                            fname, typ = win32api.RegQueryValueEx(hplatform, None)
                            if typ == win32con.REG_EXPAND_SZ:
                                fname = win32api.ExpandEnvironmentStrings(fname)
                        except win32api.error:
                            fname = ""
                        collected.append((lcid, platform, fname))
                        lcidnum = lcidnum + 1
                    win32api.RegCloseKey(lcidkey)
                except ValueError:
                    pass
            num = num + 1
    finally:
        win32api.RegCloseKey(key)

    return fname, lcid
Esempio n. 2
0
def normalize_path(file):
    file = win32api.ExpandEnvironmentStrings(file)
    if file.startswith("%System%"):
        file = file.replace("%System%", win32api.GetSystemDirectory())
    elif file.startswith("%DesktopDir%"):
        desktop = win32api.ExpandEnvironmentStrings("%UserProfile%")
        desktop = desktop + os.path.sep + 'Desktop'
        file = file.replace("%DesktopDir%", desktop)
    elif file.startswith("%Programs%"):
        progs = win32api.ExpandEnvironmentStrings("%UserProfile%")
        progs = progs + os.path.sep + 'Start Menu' + os.path.sep + 'Programs'
        file = file.replace("%Programs%", progs)
    return file
Esempio n. 3
0
def EnumTlbs(excludeFlags=0):
    """Return a list of TypelibSpec objects, one for each registered library."""
    key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "Typelib")
    iids = EnumKeys(key)
    results = []
    for iid, crap in iids:
        try:
            key2 = win32api.RegOpenKey(key, str(iid))
        except win32api.error:
            # A few good reasons for this, including "access denied".
            continue
        for version, tlbdesc in EnumKeys(key2):
            major_minor = version.split(".", 1)
            if len(major_minor) < 2:
                major_minor.append("0")
            # For some reason, this code used to assume the values were hex.
            # This seems to not be true - particularly for CDO 1.21
            # *sigh* - it appears there are no rules here at all, so when we need
            # to know the info, we must load the tlb by filename and request it.
            # The Resolve() method on the TypelibSpec does this.
            # For this reason, keep the version numbers as strings - that
            # way we can't be wrong!  Let code that really needs an int to work
            # out what to do.  FWIW, http://support.microsoft.com/kb/816970 is
            # pretty clear that they *should* be hex.
            major = major_minor[0]
            minor = major_minor[1]
            key3 = win32api.RegOpenKey(key2, str(version))
            try:
                # The "FLAGS" are at this point
                flags = int(win32api.RegQueryValue(key3, "FLAGS"))
            except (win32api.error, ValueError):
                flags = 0
            if flags & excludeFlags == 0:
                for lcid, crap in EnumKeys(key3):
                    try:
                        lcid = int(lcid)
                    except ValueError:  # not an LCID entry
                        continue
                    # Check for both "{lcid}\win32" and "{lcid}\win64" keys.
                    try:
                        key4 = win32api.RegOpenKey(key3,
                                                   "%s\\win32" % (lcid, ))
                    except win32api.error:
                        try:
                            key4 = win32api.RegOpenKey(key3,
                                                       "%s\\win64" % (lcid, ))
                        except win32api.error:
                            continue
                    try:
                        dll, typ = win32api.RegQueryValueEx(key4, None)
                        if typ == win32con.REG_EXPAND_SZ:
                            dll = win32api.ExpandEnvironmentStrings(dll)
                    except win32api.error:
                        dll = None
                    spec = TypelibSpec(iid, lcid, major, minor, flags)
                    spec.dll = dll
                    spec.desc = tlbdesc
                    spec.ver_desc = tlbdesc + " (" + version + ")"
                    results.append(spec)
    return results
Esempio n. 4
0
def getenv_system(varname, default=''):
    '''
        return system environment variable
    '''
    import os
    import win32api
    import win32con
    import platform  # For getting the operating system name

    if platform.system() != 'Windows':
        return os.environ(varname)
    else:
        v = default
        try:
            rkey = win32api.RegOpenKey(
                win32con.HKEY_LOCAL_MACHINE,
                'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment'
            )
            try:
                v = str(win32api.RegQueryValueEx(rkey, varname)[0])
                v = win32api.ExpandEnvironmentStrings(v)
            except:
                pass
        finally:
            win32api.RegCloseKey(rkey)
        return v
Esempio n. 5
0
def get_cmake_path():
    program = 'cmake.exe'
    path = shutil.which(program)
    if path:
        return path

    path = os.path.join(
        shell.SHGetFolderPath(0, shellcon.CSIDL_PROGRAM_FILES, None, 0),
        'CMake', 'bin', program)
    if os.path.isfile(path):
        return path

    path = os.path.join(
        shell.SHGetFolderPath(0, shellcon.CSIDL_PROGRAM_FILESX86, None, 0),
        'CMake', 'bin', program)
    if os.path.isfile(path):
        return path

    #http://stackoverflow.com/questions/445139/how-to-get-program-files-folder-path-not-program-files-x86-from-32bit-wow-pr
    szNativeProgramFilesFolder = win32api.ExpandEnvironmentStrings(
        "%ProgramW6432%")
    path = os.path.join(szNativeProgramFilesFolder, 'CMake', 'bin', program)
    if os.path.isfile(path):
        return path

    return None
Esempio n. 6
0
    def get_commands_for_application(application):
        ret = []
        hkey = None
        #print "get_commands_for_application",application

        for action in ["open", "edit", "read"]:
            try:
                #print "t0",r"%s\shell\%s\command"%(application, action)
                hkey = win32api.RegOpenKey(
                    win32con.HKEY_CLASSES_ROOT,
                    r"%s\shell\%s\command" % (application, action), 0,
                    win32con.KEY_QUERY_VALUE)

                (command, _) = win32api.RegQueryValueEx(hkey, None)
                command = win32api.ExpandEnvironmentStrings(command)
                command = MimeTypeInfos.transform_command(command)

                if command not in ret:
                    ret.append(command)
            except:
                pass
            finally:
                if hkey is not None:
                    win32api.RegCloseKey(hkey)

        return ret
Esempio n. 7
0
def loadDLL(dllName):

    dllPath = win32api.ExpandEnvironmentStrings(dllName)
    LOGGER.debug("Loading library {}".format(dllPath))
    dllHandle = win32api.LoadLibraryEx(dllPath, 0,
                                       win32con.LOAD_LIBRARY_AS_DATAFILE)
    return dllHandle
Esempio n. 8
0
def main():

    with open("./service_bin.txt", "w") as fd:

        read_perm = ( win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE )

        hkey = win32api.RegOpenKeyEx( win32con.HKEY_LOCAL_MACHINE, "SYSTEM\ControlSet001\Services", 0, read_perm )


        names = [ data[0] for data in win32api.RegEnumKeyEx(hkey) ]

        for name in names:

            name = name.lower()
            fd.write("=========== %s ============\n" % name)
#            print("=========== %s ============" % name)

            # Image Path
            try:
                subkey = win32api.RegOpenKeyEx( hkey, name, 0, read_perm )
                image_path = win32api.RegQueryValueEx( subkey, "ImagePath" )
                path = win32api.ExpandEnvironmentStrings( image_path[0] )
                path = path.lower()

            except pywintypes.error:
                path = ""

            fd.write("Image Path: %s\n" % path)
#            print("Image Path: ", path)


            # Service DLL
            try:
                subkey = win32api.RegOpenKeyEx( hkey, "%s\Parameters" % name, 0, read_perm )
                service_dll = win32api.RegQueryValueEx( subkey, "ServiceDll" )
                path = win32api.ExpandEnvironmentStrings( service_dll[0] )
                path = path.lower()

            except pywintypes.error as e:
                path = ""

            fd.write("Service DLL: %s\n" % path)
#            print("Service DLL: ", path)

            fd.write("\n\n")
Esempio n. 9
0
def get_extension_defn(moduleName, mapFileName):
    if win32api is None: return None
    dsp = win32api.GetProfileVal(moduleName, "dsp", "", mapFileName)
    if dsp=="":
        print 'warning: dsp not found'
        return None

    # We allow environment variables in the file name
    dsp = win32api.ExpandEnvironmentStrings(dsp)
    # If the path to the .DSP file is not absolute, assume it is relative
    # to the description file.
    if not os.path.isabs(dsp):
        dsp = os.path.join( os.path.split(mapFileName)[0], dsp)
    # Parse it to extract the source files.
    sourceFiles = parse_dsp(dsp)
    if sourceFiles is None:
        print 'warning: no source files'
        return None

    module = CExtension(moduleName, sourceFiles)
    # Put the path to the DSP into the environment so entries can reference it.
    os.environ['dsp_path'] = os.path.split(dsp)[0]
    os.environ['ini_path'] = os.path.split(mapFileName)[0]

    cl_options = win32api.GetProfileVal(moduleName, "cl", "", mapFileName)
    if cl_options:
        module.AddCompilerOption(win32api.ExpandEnvironmentStrings(cl_options))

    exclude = win32api.GetProfileVal(moduleName, "exclude", "", mapFileName)
    exclude = string.split(exclude)

    if win32api.GetProfileVal(moduleName, "Unicode", 0, mapFileName):
        module.AddCompilerOption('/D UNICODE /D _UNICODE')

    libs = string.split(win32api.GetProfileVal(moduleName, "libs", "", mapFileName))
    for lib in libs:
        module.AddLinkerLib(win32api.ExpandEnvironmentStrings(lib))

    for exc in exclude:
        if exc in module.sourceFiles:
            modules.sourceFiles.remove(exc)

    return module
def _RegQueryValue(key, value, default=None):
    try:
        data, typ = win32api.RegQueryValueEx(key, value)
    except win32api.error:
        return default
    if typ == win32con.REG_EXPAND_SZ:
        data = win32api.ExpandEnvironmentStrings(data)
    if type in (win32con.REG_EXPAND_SZ, win32con.REG_SZ):
        # Occasionally see trailing \0 chars.
        data = data.rstrip('\0')
    return data
Esempio n. 11
0
def get_profile_dir(username):
    """Return the user's profile directory."""
    import _winreg, win32api
    sid = win32security.ConvertSidToStringSid(
            win32security.LookupAccountName(None, username)[0])
    try:
        key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
          r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"+"\\"+sid)
    except WindowsError:
        raise ftpserver.AuthorizerError("No profile directory defined for %s "
                                        "user" %username)
    value = _winreg.QueryValueEx(key, "ProfileImagePath")[0]
    return win32api.ExpandEnvironmentStrings(value)
Esempio n. 12
0
def FormatMessage(eventLogRecord, logType="Application"):
    """Given a tuple from ReadEventLog, and optionally where the event
    record came from, load the message, and process message inserts.

    Note that this function may raise win32api.error.  See also the
    function SafeFormatMessage which will return None if the message can
    not be processed.
    """

    # From the event log source name, we know the name of the registry
    # key to look under for the name of the message DLL that contains
    # the messages we need to extract with FormatMessage. So first get
    # the event log source name...
    keyName = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (
        logType,
        eventLogRecord.SourceName,
    )

    # Now open this key and get the EventMessageFile value, which is
    # the name of the message DLL.
    handle = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyName)
    try:
        dllNames = win32api.RegQueryValueEx(handle,
                                            "EventMessageFile")[0].split(";")
        # Win2k etc appear to allow multiple DLL names
        data = None
        for dllName in dllNames:
            try:
                # Expand environment variable strings in the message DLL path name,
                # in case any are there.
                dllName = win32api.ExpandEnvironmentStrings(dllName)

                dllHandle = win32api.LoadLibraryEx(
                    dllName, 0, win32con.LOAD_LIBRARY_AS_DATAFILE)
                try:
                    data = win32api.FormatMessageW(
                        win32con.FORMAT_MESSAGE_FROM_HMODULE,
                        dllHandle,
                        eventLogRecord.EventID,
                        langid,
                        eventLogRecord.StringInserts,
                    )
                finally:
                    win32api.FreeLibrary(dllHandle)
            except win32api.error:
                pass  # Not in this DLL - try the next
            if data is not None:
                break
    finally:
        win32api.RegCloseKey(handle)
    return data or ""  # Don't want "None" ever being returned.
Esempio n. 13
0
def getenv_system(varname, default=''):
    v = default
    try:
        rkey = win32api.RegOpenKey(
            win32con.HKEY_LOCAL_MACHINE,
            'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment')
        try:
            v = str(win32api.RegQueryValueEx(rkey, varname)[0])
            v = win32api.ExpandEnvironmentStrings(v)
        except:
            pass
    finally:
        win32api.RegCloseKey(rkey)
    return v
Esempio n. 14
0
 def get_env_variable(var_name, default=''):
     key = default
     try:
         rkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE,
                                    (r'SYSTEM\CurrentControlSet\Control'
                                     r'\Session Manager\Environment'))
         try:
             key = str(win32api.RegQueryValueEx(rkey, var_name)[0])
             key = win32api.ExpandEnvironmentStrings(key)
         except Exception:  # noqa
             pass
     finally:
         win32api.RegCloseKey(rkey)
     return key
Esempio n. 15
0
 def get_home_dir(self, username):
     """Return the user's profile directory, the closest thing
     to a user home directory we have on Windows.
     """
     try:
         sid = win32security.ConvertSidToStringSid(
             win32security.LookupAccountName(None, username)[0])
     except pywintypes.error as err:
         raise AuthorizerError(err)
     path = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" + \
            "\\" + sid
     try:
         key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path)
     except WindowsError:
         raise AuthorizerError(
             "No profile directory defined for user %s" % username)
     value = _winreg.QueryValueEx(key, "ProfileImagePath")[0]
     return win32api.ExpandEnvironmentStrings(value)
Esempio n. 16
0
def get_windows_reg_env(varname, default=''):
    """
        asks for paths commonly used but not exposed as ENVs
        in english Windows 2003 those are:
        'AppData' = %USERPROFILE%\Application Data (also an ENV)
        'Desktop' = %USERPROFILE%\Desktop
        'Favorites' = %USERPROFILE%\Favorites
        'NetHood' = %USERPROFILE%\NetHood
        'Personal' = D:\My Documents (PATH TO MY DOCUMENTS)
        'PrintHood' = %USERPROFILE%\PrintHood
        'Programs' = %USERPROFILE%\Start Menu\Programs
        'Recent' = %USERPROFILE%\Recent
        'SendTo' = %USERPROFILE%\SendTo
        'Start Menu' = %USERPROFILE%\Start Menu
        'Startup' = %USERPROFILE%\Start Menu\Programs\Startup
        'Templates' = %USERPROFILE%\Templates
        'My Pictures' = D:\My Documents\My Pictures
        'Local Settings' = %USERPROFILE%\Local Settings
        'Local AppData' = %USERPROFILE%\Local Settings\Application Data
        'Cache' = %USERPROFILE%\Local Settings\Temporary Internet Files
        'Cookies' = %USERPROFILE%\Cookies
        'History' = %USERPROFILE%\Local Settings\History
    """

    if os.name != 'nt':
        return ''

    val = default
    try:
        rkey = win32api.RegOpenKey(
            win32con.HKEY_CURRENT_USER,
            r'Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders'
        )
        try:
            val = str(win32api.RegQueryValueEx(rkey, varname)[0])
            val = win32api.ExpandEnvironmentStrings(
                val)  # expand using environ
        except:
            pass

    finally:
        win32api.RegCloseKey(rkey)

    return val
def _get_firefox_nt_cookie_jar ():
    # See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473846
    try:
        import _winreg
        import win32api
    except ImportError:
        logging.error('Cannot load winreg -- running windows and win32api loaded?')
    key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
    try:
        result = _winreg.QueryValueEx(key, 'AppData')
    except WindowsError:
        return None
    else:
        key.Close()
        if ret[1] == _winreg.REG_EXPAND_SZ:
            result = win32api.ExpandEnvironmentStrings(ret[0])
        else:
            result = ret[0]
 
    return _get_firefox_cookie_jar(os.path.join(result, r'Mozilla\Firefox\Profiles'))
Esempio n. 18
0
def get_app_path(appname):
    r"""Look up in Windows registry for full path to application executable.
    Typically, applications create subkey with their basename
    in HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\

    :param  appname:    name of application (if no filename extension
                        is specified, .exe used)
    :return:    full path to aplication executable from registry,
                or appname itself if nothing found.
    """
    import _winreg

    basename = appname
    if not os.path.splitext(basename)[1]:
        basename = appname + '.exe'

    try:
        hkey = _winreg.OpenKey(
            _winreg.HKEY_LOCAL_MACHINE,
            'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\' +
            basename)
    except EnvironmentError:
        return appname

    try:
        try:
            path, type_id = _winreg.QueryValueEx(hkey, '')
        except WindowsError:
            return appname
    finally:
        _winreg.CloseKey(hkey)

    if type_id == REG_SZ:
        return path
    if type_id == REG_EXPAND_SZ and has_win32api:
        fullpath = win32api.ExpandEnvironmentStrings(path)
        if len(fullpath) > 1 and fullpath[0] == '"' and fullpath[-1] == '"':
            fullpath = fullpath[1:-1]  # remove quotes around value
        return fullpath
    return appname
Esempio n. 19
0
 def get_home_dir(self, username):
     """Return the user's profile directory, the closest thing
     to a user home directory we have on Windows.
     """
     try:
         sid = win32security.ConvertSidToStringSid(
             win32security.LookupAccountName(None, username)[0])
     except pywintypes.error:
         err = sys.exc_info()[1]
         raise AuthorizerError(err)
     path = r"SOFTWARE\Microsoft\Windows NT" \
            r"\CurrentVersion\ProfileList" + "\\" + sid
     try:
         key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
     except WindowsError:
         raise AuthorizerError(
             "No profile directory defined for user %s" % username)
     value = winreg.QueryValueEx(key, "ProfileImagePath")[0]
     home = win32api.ExpandEnvironmentStrings(value)
     if not PY3 and not isinstance(home, unicode):
         home = home.decode('utf8')
     return home
    def getIcon(self, filename):
        Logger.debug("ApplicationsDetection::getIcon %s" % (filename))
        if not os.path.exists(filename):
            Logger.warn("ApplicationsDetection::getIcon no such file")
            return None

        pythoncom.CoInitialize()

        if win32process.IsWow64Process():
            wow64_value = Util.Wow64DisableWow64FsRedirection()

        shortcut = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None,
                                              pythoncom.CLSCTX_INPROC_SERVER,
                                              shell.IID_IShellLink)
        shortcut.QueryInterface(pythoncom.IID_IPersistFile).Load(filename)

        (iconLocation_src, iconId) = shortcut.GetIconLocation()
        iconLocation = win32api.ExpandEnvironmentStrings(iconLocation_src)

        if not os.path.exists(iconLocation) and win32process.IsWow64Process():
            iconLocation = Util.clean_wow64_path(iconLocation)

        if len(iconLocation) == 0 or not os.path.exists(iconLocation):
            Logger.debug(
                "ApplicationsDetection::getIcon No IconLocation, use shortcut target"
            )
            iconLocation = win32api.ExpandEnvironmentStrings(
                shortcut.GetPath(shell.SLGP_RAWPATH)[0])

            if not os.path.exists(
                    iconLocation) and win32process.IsWow64Process():
                iconLocation = Util.clean_wow64_path(iconLocation)

            if len(iconLocation) == 0 or not os.path.exists(iconLocation):
                Logger.warn(
                    "ApplicationsDetection::getIcon Neither IconLocation nor shortcut target on %s (%s)"
                    % (filename, iconLocation))
                if win32process.IsWow64Process():
                    Util.Revert64DisableWow64FsRedirection(wow64_value)

                return None

        if win32process.IsWow64Process():
            Util.Revert64DisableWow64FsRedirection(wow64_value)

        path_tmp = tempfile.mktemp()

        path_bmp = path_tmp + ".bmp"
        path_png = path_tmp + ".png"

        cmd = """"%s" "%s,%d" "%s" """ % ("exeIcon2png.exe", iconLocation,
                                          iconId, path_png)
        status = self.execute(cmd, True)
        if status != 0:
            Logger.warn("Unable to extract icon, use alternative method")
            Logger.debug(
                "ApplicationsDetection::getIcon following command returned %d: %s"
                % (status, cmd))
            if os.path.exists(path_png):
                os.remove(path_png)

            cmd = """"%s" "%s" "%s" """ % ("extract_icon.exe", iconLocation,
                                           path_bmp)

            status = self.execute(cmd, True)
            if status != 0:
                Logger.warn(
                    "Unable to extract icon with the alternative method")
                Logger.debug(
                    "ApplicationsDetection::getIcon following command returned %d: %s"
                    % (status, cmd))
                if os.path.exists(path_bmp):
                    os.remove(path_bmp)

                return None

            if not os.path.exists(path_bmp):
                Logger.debug(
                    "ApplicationsDetection::getIcon No bmp file returned")
                return None

            cmd = """"%s" -Q -O "%s" "%s" """ % ("bmp2png.exe", path_png,
                                                 path_bmp)
            status = self.execute(cmd, True)
            if status != 0:
                Logger.warn(
                    "Unable to extract icon with the alternative method")
                Logger.debug(
                    "ApplicationsDetection::getIcon following command returned %d: %s"
                    % (status, cmd))
                os.remove(path_bmp)
                if os.path.exists(path_png):
                    os.remove(path_png)

                return None

            os.remove(path_bmp)

        if not os.path.exists(path_png):
            Logger.debug("ApplicationsDetection::getIcon No png file returned")
            return None

        f = open(path_png, 'rb')
        buffer = f.read()
        f.close()

        os.remove(path_png)
        return buffer
Esempio n. 21
0
"""Extension management for Windows.
Esempio n. 22
0
def EnumTypeLib():
    ret = []
    libKeys = []
    key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib")
    try:
        num = 0
        while 1:
            try:
                keyName = win32api.RegEnumKey(key, num)
                #print keyName
            except win32api.error:
                break
            # Enumerate all version info
            subKey = win32api.RegOpenKey(key, keyName)
            name = None
            try:
                subNum = 0
                bestVersion = 0.0
                while 1:
                    try:
                        versionStr = win32api.RegEnumKey(subKey, subNum)
                    except win32api.error:
                        break
                    try:
                        versionFlt = float(versionStr)
                    except ValueError:
                        versionFlt = 0 # ????
                    if versionFlt > bestVersion:
                        bestVersion = versionFlt
                        name = win32api.RegQueryValue(subKey, versionStr)
                    subNum = subNum + 1
            finally:
                win32api.RegCloseKey(subKey)
            if name is not None:
                libKeys.append((keyName, versionStr))
                #print name
            num += 1
    except:
        pass

    for keyName, versionStr in libKeys:
        key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib\\%s\\%s" % (keyName, versionStr))
        num = 0
        while True:
            try:
                subKey = win32api.RegEnumKey(key, num)

                #print subKey
            except:
                break
            hSubKey = win32api.RegOpenKey(key, subKey)
            try:
                value, typ = win32api.RegQueryValueEx(hSubKey, None)
                if typ == win32con.REG_EXPAND_SZ:
                    value = win32api.ExpandEnvironmentStrings(value)
            except:
                value = ""
            if subKey=="HELPDIR":
                helpPath = value
            elif subKey.lower()=="flags":
                flags = value
            else:
                try:
                    lcid = int(subKey)
                    #print key
                    #print key, subKey
                    lcidkey = win32api.RegOpenKey(key, subKey)
                    #print lcidkey
                    # Enumerate the platforms
                    lcidnum = 0
                    while 1:
                        try:
                            platform = win32api.RegEnumKey(lcidkey, lcidnum)
                            #print platform
                        except Exception, e:
                            #print 111,e
                            break
                        try:
                            hplatform = win32api.RegOpenKey(lcidkey, platform)
                            fname, typ = win32api.RegQueryValueEx(hplatform, None)
                            if fname != None:
                                ret.append((fname, keyName))
                                #print key2
                            #print fname
                            #print lcid, platform, fname

                            #if typ == win32con.REG_EXPAND_SZ:
                                #fname = win32api.ExpandEnvironmentStrings(fname)
                                #print fname
                        except win32api.error:
                            fname = ""
                        #collected.append((lcid, platform, fname))
                        lcidnum = lcidnum + 1
                    win32api.RegCloseKey(lcidkey)
                except ValueError,e:
                    #print e
                    pass
            num += 1
def Main():
    cgiEnv = lib_common.CgiEnv()
    clsidstr = cgiEnv.GetId()

    grph = cgiEnv.GetGraph()

    versions = lib_com_type_lib.ComKeyAllNameVersion(
        lib_com_type_lib.TypeLibRegistryKey, clsidstr)

    # typelibNode = lib_common.gUriGen.ComRegisteredTypeLibUri( clsidstr )

    ###################  See Win32_ComClass !!!!

    for versionStr, name in list(versions.items()):
        sys.stderr.write("Vers=%s Name=%s\n" % (versionStr, name))

        # TODO: The top of the tree does not make sense.

        #strVersion = "Version=%.1f" % ( versionStr )
        #nodeDllVersionNode = lib_common.gUriGen.FileUri( "DLL" + name )
        #versionNode = lib_common.gUriGen.FileUri( name )
        #grph.add( (versionNode, pc.property_information, lib_common.NodeLiteral("name="+name) ) )
        #grph.add( (versionNode, pc.property_information, lib_common.NodeLiteral(strVersion) ) )
        #grph.add( (typelibNode, pc.property_com_version, versionStr ) )

        typelibNode = lib_com_type_lib.CreateComRegisteredTypeLibNode(
            grph, clsidstr, name, versionStr)

        # collected = []
        helpPath = ""

        try:
            key = win32api.RegOpenKey(
                win32con.HKEY_CLASSES_ROOT,
                "TypeLib\\%s\\%s" % (clsidstr, versionStr))
        except Exception:
            exc = sys.exc_info()[1]
            lib_common.ErrorMessageHtml("win32api.RegOpenKey clsidstr=" +
                                        str(clsidstr) + " versionStr=" +
                                        str(versionStr) + ". Caught:" +
                                        str(exc))

        try:
            num = 0
            while True:
                try:
                    subKey = win32api.RegEnumKey(key, num)
                except win32api.error:
                    break
                hSubKey = win32api.RegOpenKey(key, subKey)
                try:
                    value, typ = win32api.RegQueryValueEx(hSubKey, None)
                    if typ == win32con.REG_EXPAND_SZ:
                        value = win32api.ExpandEnvironmentStrings(value)
                except win32api.error:
                    value = ""
                if subKey == "HELPDIR":
                    helpPath = value
                elif subKey == "Flags":
                    flags = value
                else:
                    try:
                        # lcid = localeid
                        lcid = int(subKey)
                        lcidkey = win32api.RegOpenKey(key, subKey)
                        # Enumerate the platforms
                        lcidnum = 0
                        while 1:
                            try:
                                platform = win32api.RegEnumKey(
                                    lcidkey, lcidnum)
                            except win32api.error:
                                break
                            try:
                                hplatform = win32api.RegOpenKey(
                                    lcidkey, platform)
                                fname, typ = win32api.RegQueryValueEx(
                                    hplatform, None)
                                if typ == win32con.REG_EXPAND_SZ:
                                    fname = win32api.ExpandEnvironmentStrings(
                                        fname)
                            except win32api.error:
                                fname = ""

                            # Ligne 189
                            # collected.append((lcid, platform, fname))
                            # ret.append(HLITypeLib(fname, "Type Library" + extraDesc))

                            fnameMysteryNode = lib_common.gUriGen.ComTypeLibUri(
                                fname)
                            grph.add(
                                (fnameMysteryNode, pc.property_information,
                                 lib_common.NodeLiteral("lcid=%d" % lcid)))
                            grph.add(
                                (fnameMysteryNode, pc.property_information,
                                 lib_common.NodeLiteral("platform=" +
                                                        platform)))
                            grph.add((typelibNode, pc.property_com_version,
                                      fnameMysteryNode))

                            lcidnum = lcidnum + 1
                        win32api.RegCloseKey(lcidkey)
                    except ValueError:
                        pass
                num = num + 1
        finally:
            win32api.RegCloseKey(key)

    cgiEnv.OutCgiRdf()
Esempio n. 24
0
 def GetSubList(self):
     import os
     clsidstr, versionStr = self.myobject
     collected = []
     helpPath = ""
     key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT,
                               "TypeLib\\%s\\%s" % (clsidstr, versionStr))
     win32ui.DoWaitCursor(1)
     try:
         num = 0
         while 1:
             try:
                 subKey = win32api.RegEnumKey(key, num)
             except win32api.error:
                 break
             hSubKey = win32api.RegOpenKey(key, subKey)
             try:
                 value, typ = win32api.RegQueryValueEx(hSubKey, None)
                 if typ == win32con.REG_EXPAND_SZ:
                     value = win32api.ExpandEnvironmentStrings(value)
             except win32api.error:
                 value = ""
             if subKey == "HELPDIR":
                 helpPath = value
             elif subKey == "Flags":
                 flags = value
             else:
                 try:
                     lcid = int(subKey)
                     lcidkey = win32api.RegOpenKey(key, subKey)
                     # Enumerate the platforms
                     lcidnum = 0
                     while 1:
                         try:
                             platform = win32api.RegEnumKey(
                                 lcidkey, lcidnum)
                         except win32api.error:
                             break
                         try:
                             hplatform = win32api.RegOpenKey(
                                 lcidkey, platform)
                             fname, typ = win32api.RegQueryValueEx(
                                 hplatform, None)
                             if typ == win32con.REG_EXPAND_SZ:
                                 fname = win32api.ExpandEnvironmentStrings(
                                     fname)
                         except win32api.error:
                             fname = ""
                         collected.append((lcid, platform, fname))
                         lcidnum = lcidnum + 1
                     win32api.RegCloseKey(lcidkey)
                 except ValueError:
                     pass
             num = num + 1
     finally:
         win32ui.DoWaitCursor(0)
         win32api.RegCloseKey(key)
     # Now, loop over my collected objects, adding a TypeLib and a HelpFile
     ret = []
     #               if helpPath: ret.append(browser.MakeHLI(helpPath, "Help Path"))
     ret.append(HLICLSID(clsidstr))
     for lcid, platform, fname in collected:
         extraDescs = []
         if platform != "win32":
             extraDescs.append(platform)
         if lcid:
             extraDescs.append("locale=%s" % lcid)
         extraDesc = ""
         if extraDescs: extraDesc = " (%s)" % ", ".join(extraDescs)
         ret.append(HLITypeLib(fname, "Type Library" + extraDesc))
     ret.sort()
     return ret
Esempio n. 25
0
def SafeExpandEnvironmentStrings(s):
    if sys.platform.startswith('win'):
        try:
            s = win32api.ExpandEnvironmentStrings(s)
        except Exception, e:
            print "An Error occured in ExpandEnvironmentStrings: %s" % str(e)
Esempio n. 26
0
    completeVers = "TypeLib\%s\%s" % (clsidstr, versionStr)
    sys.stderr.write("completeVers=%s\n" % (completeVers))
    key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, completeVers)

    try:
        num = 0
        while 1:
            try:
                subKey = win32api.RegEnumKey(key, num)
            except win32api.error:
                break
            hSubKey = win32api.RegOpenKey(key, subKey)
            try:
                value, typ = win32api.RegQueryValueEx(hSubKey, None)
                if typ == win32con.REG_EXPAND_SZ:
                    value = win32api.ExpandEnvironmentStrings(value)
            except win32api.error:
                value = ""
            if subKey == "HELPDIR":
                helpPath = value
            elif subKey == "Flags":
                flags = value
            else:
                try:
                    lcid = int(subKey)
                    lcidkey = win32api.RegOpenKey(key, subKey)
                    # Enumerate the platforms
                    lcidnum = 0
                    while 1:
                        try:
                            platform = win32api.RegEnumKey(lcidkey, lcidnum)
Esempio n. 27
0
    class BaseWindowsAuthorizer(object):
        """An authorizer compatible with Windows user account and
        password database.
        This class should not be used directly unless for subclassing.
        Use higher-level WinowsAuthorizer class instead.
        """

        def __init__(self, anonymous_user=None, anonymous_password=None):
            # actually try to impersonate the user
            self.anonymous_user = anonymous_user
            self.anonymous_password = anonymous_password
            if self.anonymous_user is not None:
                self.impersonate_user(self.anonymous_user,
                                      self.anonymous_password)
                self.terminate_impersonation()

        def validate_authentication(self, username, password):
            if username == "anonymous":
                return self.anonymous_user is not None
            try:
                win32security.LogonUser(username, None, password,
                                        win32con.LOGON32_LOGON_INTERACTIVE,
                                        win32con.LOGON32_PROVIDER_DEFAULT)
            except pywintypes.error:
                return False
            else:
                return True

        @replace_anonymous
        def impersonate_user(self, username, password):
            """Impersonate the security context of another user."""
            handler = win32security.LogonUser(username, None, password,
                                              win32con.LOGON32_LOGON_INTERACTIVE,
                                              win32con.LOGON32_PROVIDER_DEFAULT)
            win32security.ImpersonateLoggedOnUser(handler)
            handler.Close()

        def terminate_impersonation(self, username):
            """Terminate the impersonation of another user."""
            win32security.RevertToSelf()

        @replace_anonymous
        def has_user(self, username):
            return username in self._get_system_users()

        @replace_anonymous
        def get_home_dir(self, username):
            """Return the user's profile directory, the closest thing
            to a user home directory we have on Windows.
            """
            try:
                sid = win32security.ConvertSidToStringSid(
                        win32security.LookupAccountName(None, username)[0])
            except pywintypes.error, err:
                raise AuthorizerError(err)
            path = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" + \
                   "\\" + sid
            try:
                key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path)
            except WindowsError:
                raise AuthorizerError("No profile directory defined for user %s"
                                      % username)
            value = _winreg.QueryValueEx(key, "ProfileImagePath")[0]
            return win32api.ExpandEnvironmentStrings(value)