Beispiel #1
0
def __FindSvcDeps(findName):
    if isinstance(findName, pywintypes.UnicodeType):
        findName = str(findName)
    dict = {}
    k = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE,
                            "SYSTEM\\CurrentControlSet\\Services")
    num = 0
    while True:
        try:
            svc = win32api.RegEnumKey(k, num)
        except win32api.error:
            break
        num = num + 1
        sk = win32api.RegOpenKey(k, svc)
        try:
            deps, typ = win32api.RegQueryValueEx(sk, "DependOnService")
        except win32api.error:
            deps = ()
        for dep in deps:
            dep = dep.lower()
            dep_on = dict.get(dep, [])
            dep_on.append(svc)
            dict[dep] = dep_on

    return __ResolveDeps(findName, dict)
Beispiel #2
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
                    # Only care about "{lcid}\win32" key - jump straight there.
                    try:
                        key4 = win32api.RegOpenKey(key3, "%s\\win32" % (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
Beispiel #3
0
def UnregisterHelpFile(helpFile, helpDesc=None):
    """Unregister a help file in the registry.

       helpFile -- the base name of the help file.
       helpDesc -- A description for the help file.  If None, the helpFile param is used.
    """
    key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE,
                              "Software\\Microsoft\\Windows\\Help", 0,
                              win32con.KEY_ALL_ACCESS)
    try:
        try:
            win32api.RegDeleteValue(key, helpFile)
        except win32api.error as exc:
            import winerror
            if exc.winerror != winerror.ERROR_FILE_NOT_FOUND:
                raise
    finally:
        win32api.RegCloseKey(key)

    # Now de-register with Python itself.
    if helpDesc is None:
        helpDesc = helpFile
    try:
        win32api.RegDeleteKey(
            GetRootKey(),
            BuildDefaultPythonKey() + "\\Help\\%s" % helpDesc)
    except win32api.error as exc:
        import winerror
        if exc.winerror != winerror.ERROR_FILE_NOT_FOUND:
            raise
Beispiel #4
0
def recurse_delete_key(path, base=win32con.HKEY_CLASSES_ROOT):
    """Recursively delete registry keys.

    This is needed since you can't blast a key when subkeys exist.
    """
    try:
        h = win32api.RegOpenKey(base, path)
    except win32api.error as xxx_todo_changeme2:
        (code, fn, msg) = xxx_todo_changeme2.args
        if code != winerror.ERROR_FILE_NOT_FOUND:
            raise win32api.error(code, fn, msg)
    else:
        # parent key found and opened successfully. do some work, making sure
        # to always close the thing (error or no).
        try:
            # remove all of the subkeys
            while True:
                try:
                    subkeyname = win32api.RegEnumKey(h, 0)
                except win32api.error as xxx_todo_changeme:
                    (code, fn, msg) = xxx_todo_changeme.args
                    if code != winerror.ERROR_NO_MORE_ITEMS:
                        raise win32api.error(code, fn, msg)
                    break
                recurse_delete_key(path + '\\' + subkeyname, base)

            # remove the parent key
            _remove_key(path, base)
        finally:
            win32api.RegCloseKey(h)
Beispiel #5
0
def GetRootKey():
    """Retrieves the Registry root in use by Python.
    """
    keyname = BuildDefaultPythonKey()
    try:
        k = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyname)
        k.close()
        return win32con.HKEY_CURRENT_USER
    except win32api.error:
        return win32con.HKEY_LOCAL_MACHINE
Beispiel #6
0
 def GetSubList(self):
     # Explicit lookup in the registry.
     ret = []
     key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib")
     win32ui.DoWaitCursor(1)
     try:
         num = 0
         while True:
             try:
                 keyName = win32api.RegEnumKey(key, num)
             except win32api.error:
                 break
             # Enumerate all version info
             subKey = win32api.RegOpenKey(key, keyName)
             name = None
             try:
                 subNum = 0
                 bestVersion = 0.0
                 while True:
                     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:
                 ret.append(
                     HLIRegisteredTypeLibrary((keyName, versionStr), name))
             num = num + 1
     finally:
         win32api.RegCloseKey(key)
         win32ui.DoWaitCursor(0)
     ret.sort()
     return ret
Beispiel #7
0
def LocateSpecificServiceExe(serviceName):
    # Given the name of a specific service, return the .EXE name _it_ uses
    # (which may or may not be the Python Service EXE
    hkey = win32api.RegOpenKey(
        win32con.HKEY_LOCAL_MACHINE,
        "SYSTEM\\CurrentControlSet\\Services\\%s" % (serviceName), 0,
        win32con.KEY_ALL_ACCESS)
    try:
        return win32api.RegQueryValueEx(hkey, "ImagePath")[0]
    finally:
        hkey.Close()
Beispiel #8
0
def CheckRegisteredModules(verbose):
    # Check out all registered modules.
    k = regutil.BuildDefaultPythonKey() + "\\Modules"
    try:
        keyhandle = win32api.RegOpenKey(regutil.GetRootKey(), k)
        print("WARNING: 'Modules' registry entry is deprectated and evil!")
    except win32api.error as exc:
        import winerror
        if exc.winerror != winerror.ERROR_FILE_NOT_FOUND:
            raise
        return
Beispiel #9
0
def InstallPerfmonForService(serviceName, iniName, dllName=None):
    # If no DLL name, look it up in the INI file name
    if not dllName:  # May be empty string!
        dllName = win32api.GetProfileVal("Python", "dll", "", iniName)
    # Still not found - look for the standard one in the same dir as
    # win32service.pyd
    if not dllName:
        try:
            tryName = os.path.join(
                os.path.split(win32service.__file__)[0], "perfmondata.dll")
            if os.path.isfile(tryName):
                dllName = tryName
        except AttributeError:
            # Frozen app? - anyway, can't find it!
            pass
    if not dllName:
        raise ValueError("The name of the performance DLL must be available")
    dllName = win32api.GetFullPathName(dllName)
    # Now setup all the required "Performance" entries.
    hkey = win32api.RegOpenKey(
        win32con.HKEY_LOCAL_MACHINE,
        "SYSTEM\\CurrentControlSet\\Services\\%s" % (serviceName), 0,
        win32con.KEY_ALL_ACCESS)
    try:
        subKey = win32api.RegCreateKey(hkey, "Performance")
        try:
            win32api.RegSetValueEx(subKey, "Library", 0, win32con.REG_SZ,
                                   dllName)
            win32api.RegSetValueEx(subKey, "Open", 0, win32con.REG_SZ,
                                   "OpenPerformanceData")
            win32api.RegSetValueEx(subKey, "Close", 0, win32con.REG_SZ,
                                   "ClosePerformanceData")
            win32api.RegSetValueEx(subKey, "Collect", 0, win32con.REG_SZ,
                                   "CollectPerformanceData")
        finally:
            win32api.RegCloseKey(subKey)
    finally:
        win32api.RegCloseKey(hkey)
    # Now do the "Lodctr" thang...

    try:
        import perfmon
        path, fname = os.path.split(iniName)
        oldPath = os.getcwd()
        if path:
            os.chdir(path)
        try:
            perfmon.LoadPerfCounterTextStrings("python.exe " + fname)
        finally:
            os.chdir(oldPath)
    except win32api.error as details:
        print("The service was installed OK, but the performance monitor")
        print("data could not be loaded.", details)
Beispiel #10
0
def _GetServiceShortName(longName):
    # looks up a services name
    # from the display name
    # Thanks to Andy McKay for this code.
    access = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
    hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE,
                               "SYSTEM\\CurrentControlSet\\Services", 0,
                               access)
    num = win32api.RegQueryInfoKey(hkey)[0]
    longName = longName.lower()
    # loop through number of subkeys
    for x in range(0, num):
        # find service name, open subkey
        svc = win32api.RegEnumKey(hkey, x)
        skey = win32api.RegOpenKey(hkey, svc, 0, access)
        try:
            # find display name
            thisName = str(win32api.RegQueryValueEx(skey, "DisplayName")[0])
            if thisName.lower() == longName:
                return svc
        except win32api.error:
            # in case there is no key called DisplayName
            pass
    return None
Beispiel #11
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.
Beispiel #12
0
def CheckPythonPaths(verbose):
    if verbose:
        print("Python Paths:")
    # Check the core path
    if verbose:
        print("\tCore Path:", end=' ')
    try:
        appPath = win32api.RegQueryValue(
            regutil.GetRootKey(),
            regutil.BuildDefaultPythonKey() + "\\PythonPath")
    except win32api.error as exc:
        print("** does not exist - ", exc.strerror)
    problem = CheckPathString(appPath)
    if problem:
        print(problem)
    else:
        if verbose:
            print(appPath)

    key = win32api.RegOpenKey(regutil.GetRootKey(),
                              regutil.BuildDefaultPythonKey() + "\\PythonPath",
                              0, win32con.KEY_READ)
    try:
        keyNo = 0
        while True:
            try:
                appName = win32api.RegEnumKey(key, keyNo)
                appPath = win32api.RegQueryValue(key, appName)
                if verbose:
                    print("\t" + appName + ":", end=' ')
                if appPath:
                    problem = CheckPathString(appPath)
                    if problem:
                        print(problem)
                    else:
                        if verbose:
                            print(appPath)
                else:
                    if verbose:
                        print("(empty)")
                keyNo = keyNo + 1
            except win32api.error:
                break
    finally:
        win32api.RegCloseKey(key)
Beispiel #13
0
def CheckHelpFiles(verbose):
    if verbose:
        print("Help Files:")
    try:
        key = win32api.RegOpenKey(regutil.GetRootKey(),
                                  regutil.BuildDefaultPythonKey() + "\\Help",
                                  0, win32con.KEY_READ)
    except win32api.error as exc:
        import winerror
        if exc.winerror != winerror.ERROR_FILE_NOT_FOUND:
            raise
        return

    try:
        keyNo = 0
        while True:
            try:
                helpDesc = win32api.RegEnumKey(key, keyNo)
                helpFile = win32api.RegQueryValue(key, helpDesc)
                if verbose:
                    print("\t" + helpDesc + ":", end=' ')
                # query the os section.
                try:
                    os.stat(helpFile)
                    if verbose:
                        print(helpFile)
                except os.error:
                    print("** Help file %s does not exist" % helpFile)
                keyNo = keyNo + 1
            except win32api.error as exc:
                import winerror
                if exc.winerror != winerror.ERROR_NO_MORE_ITEMS:
                    raise
                break
    finally:
        win32api.RegCloseKey(key)
Beispiel #14
0
 def GetSubList(self):
     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 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 = int(subKey)
                     lcidkey = win32api.RegOpenKey(key, subKey)
                     # Enumerate the platforms
                     lcidnum = 0
                     while True:
                         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