Beispiel #1
0
def reg_get():
    try:
        return win.QueryValueEx(user_key(), 'path')[0].split(';')
    except Exception as e:
        print e
        return []
Beispiel #2
0
def currentClips():
    # return a list of clips currently being played
    key = winreg.OpenKey(cfg.regHead, cfg.regId + cfg.regClipLoc, 0,
                         winreg.KEY_ALL_ACCESS)
    return winreg.QueryValueEx(key, "currentClips")[0]
Beispiel #3
0
 def get(self, name):
     " get value out of registry "
     v, t = wreg.QueryValueEx(self.key, name)
     return v, t
Beispiel #4
0
def nowPlaying():
    key = winreg.OpenKey(cfg.regHead, cfg.regId + cfg.regLoc, 0,
                         winreg.KEY_ALL_ACCESS)
    return winreg.QueryValueEx(key, "CurrentAnim")[0]
Beispiel #5
0
def exePath():
    key = winreg.OpenKey(cfg.regHead, cfg.regId + cfg.regSystemLoc, 0,
                         winreg.KEY_ALL_ACCESS)
    return winreg.QueryValueEx(key, "MainPath")[0] + "\\vghd.exe"
Beispiel #6
0
 def getKeyValue(self):
     self.PyHKEY = self.getKey()
     self.installPath = _winreg.QueryValueEx(self.PyHKEY, self.valueName)[0]
     _winreg.CloseKey(self.PyHKEY)
     return self.installPath
Beispiel #7
0
def check_status():
    _Key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, proxy_path)
    _value, _type = _winreg.QueryValueEx(_Key, "ProxyEnable")
    return True if _value else False
Beispiel #8
0
if windows_check():
    win_7z_exes = [
        '7z.exe',
        'C:\\Program Files\\7-Zip\\7z.exe',
        'C:\\Program Files (x86)\\7-Zip\\7z.exe',
    ]

    import _winreg
    try:
        hkey = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Software\\7-Zip")
    except WindowsError:
        pass
    else:
        win_7z_path = os.path.join(
            _winreg.QueryValueEx(hkey, "Path")[0], "7z.exe")
        _winreg.CloseKey(hkey)
        win_7z_exes.insert(1, win_7z_path)

    switch_7z = "x -y"
    ## Future suport:
    ## 7-zip cannot extract tar.* with single command.
    #    ".tar.gz", ".tgz",
    #    ".tar.bz2", ".tbz",
    #    ".tar.lzma", ".tlz",
    #    ".tar.xz", ".txz",
    exts_7z = [
        ".rar",
        ".zip",
        ".tar",
        ".7z",
Beispiel #9
0
    def RegistryResolve():
        """ Return the list of dotted-quads addresses of name servers found in
        the registry -- tested on NT4 Server SP6a, Win/2000 Pro SP2, XP, ME
        (each of which has a different registry layout for nameservers!) """

        nameservers = []
        x = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
        try:
            y = _winreg.OpenKey(
                x, r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters")
        except EnvironmentError:  # so it isn't NT/2000/XP
            # Windows ME, perhaps?
            try:  # for Windows ME
                y = _winreg.OpenKey(
                    x, r"SYSTEM\CurrentControlSet\Services\VxD\MSTCP")
                nameserver, dummytype = _winreg.QueryValueEx(y, 'NameServer')
                if nameserver and not (nameserver in nameservers):
                    nameservers.extend(stringdisplay(nameserver))
            except EnvironmentError:
                pass  # Must be another Windows dialect, so who knows?
            return nameservers

        nameserver = _winreg.QueryValueEx(y, "NameServer")[0]
        if nameserver:
            nameservers = [nameserver]
        _winreg.CloseKey(y)
        try:  # for win2000
            y = _winreg.OpenKey(
                x, r"SYSTEM\CurrentControlSet\Services\Tcpip"
                r"\Parameters\DNSRegisteredAdapters")
            for i in range(1000):
                try:
                    n = _winreg.EnumKey(y, i)
                    z = _winreg.OpenKey(y, n)
                    dnscount, dnscounttype = _winreg.QueryValueEx(
                        z, 'DNSServerAddressCount')
                    dnsvalues, dnsvaluestype = _winreg.QueryValueEx(
                        z, 'DNSServerAddresses')
                    nameservers.extend(binipdisplay(dnsvalues))
                    _winreg.CloseKey(z)
                except EnvironmentError:
                    break
            _winreg.CloseKey(y)
        except EnvironmentError:
            pass

        try:  # for XP
            y = _winreg.OpenKey(
                x,
                r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces"
            )
            for i in range(1000):
                try:
                    n = _winreg.EnumKey(y, i)
                    z = _winreg.OpenKey(y, n)
                    try:
                        nameserver, dummytype = _winreg.QueryValueEx(
                            z, 'NameServer')
                        if nameserver and not (nameserver in nameservers):
                            nameservers.extend(stringdisplay(nameserver))
                        if not nameserver:  # try DhcpNameServer
                            nameserver, dummytype = _winreg.QueryValueEx(
                                z, 'DhcpNameServer')
                            if nameserver and not (nameserver in nameservers):
                                nameservers.extend(stringdisplay(nameserver))
                    except EnvironmentError:
                        pass
                    _winreg.CloseKey(z)
                except EnvironmentError:
                    break
            _winreg.CloseKey(y)
        except EnvironmentError:
            # Print "Key Interfaces not found, just do nothing"
            pass

        _winreg.CloseKey(x)
        return nameservers
Beispiel #10
0
def load_dll(win_name=None, linux_name=None):
    """Load dll or shared object file as appropriate.

    On Windows:
        If environment variable 'KVDLLPATH' is set, will try and load DLL named
        win_name from that directory. Otherwise checks registry for CANlib SDK
        installation directory.

    On Linux:
        If environment variable 'KVDLLPATH' is set, will try and load shared
        object library named linux_name from that directory. Otherwise let
        the OS try and find a matching shared library object.
    """
    dir = os.getcwd()
    installDir = os.environ.get('KVDLLPATH')
    if installDir is None or installDir == '':
        if sys.platform.startswith('win'):
            if (platform.architecture()[0] == '32bit'):
                aKeyName = r"SOFTWARE\KVASER AB\CanlibSDK"
            else:
                aKeyName = r"SOFTWARE\Wow6432Node\KVASER AB\CanlibSDK"
            aReg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
            aKey = winreg.OpenKey(aReg, aKeyName)
            aValue = winreg.QueryValueEx(aKey, "")
            baseDir = str(aValue[0])

            if 8 * struct.calcsize("P") == 32:
                installDir = os.path.join(baseDir, "Bin")
            else:
                installDir = os.path.join(baseDir, "bin_x64")
            installDir = os.path.realpath(installDir)

    if installDir is not None:
        try:
            os.chdir(installDir)
        except:
            pass  # Specified directory was not found, but it could have been empty...
        else:
            # Some DLL's are loaded "manually" so we add installDir to the PATH in
            # order to allow the OS to find them later when needed
            os.environ["PATH"] += os.pathsep + installDir

    # Load our dll and all dependencies
    loadedDll = None
    try:
        # Windows supports all dll
        if sys.platform.startswith('win'):
            dllFile = win_name
            loadedDll = ct.WinDLL(dllFile)
        elif linux_name is not None:
            dllFile = linux_name
            try:
                # First we try and find the file specified in current directory
                loadedDll = ct.CDLL(os.path.abspath(dllFile))
            except OSError:
                # Then we try and let the system find the shared library
                loadedDll = ct.CDLL(dllFile)
    except Exception as e:
        print(e)
        print("Could be a missing dependancy dll for '%s'." % dllFile)
        print("(Directory for dll: '%s')\n" % installDir)
        os.chdir(dir)
        exit(1)
    os.chdir(dir)
    return loadedDll
Beispiel #11
0
# -*- coding:utf-8 -*-

import math
import os, re, _winreg


def AddCalc(a, b):
    return a + b


def numTrans(line):
    if int(line, 16) == 0:
        return "00000000"
    else:
        wr = str(bin(int(line, 16)))
        wr = wr.replace('0b', '').zfill(32)
        # 第一个bit是最后一个字符
        # 第16个bit是第16个字符
        wr = wr[:15] + '0' + wr[16:-1] + '0'
        wr = str(hex(int(wr, 2))).replace('0x', '').replace('L', '').zfill(8)
        return wr


if __name__ == "__main__":
    htpkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\ZTE\HTP')
    htppath, type = _winreg.QueryValueEx(htpkey, "Path")
    HTP_PATH = htppath.replace('\\', '/')
    print HTP_PATH
Beispiel #12
0
    def find_binary(self):
        """Finds the binary for self.names if one was not provided."""
        binary = None
        if sys.platform in ('linux2', 'sunos5', 'solaris') \
                or sys.platform.startswith('freebsd'):
            for name in reversed(self.names):
                binary = findInPath(name)
        elif os.name == 'nt' or sys.platform == 'cygwin':

            # find the default executable from the windows registry
            try:
                import _winreg
            except ImportError:
                pass
            else:
                sam_flags = [0]
                # KEY_WOW64_32KEY etc only appeared in 2.6+, but that's OK as
                # only 2.6+ has functioning 64bit builds.
                if hasattr(_winreg, "KEY_WOW64_32KEY"):
                    if "64 bit" in sys.version:
                        # a 64bit Python should also look in the 32bit registry
                        sam_flags.append(_winreg.KEY_WOW64_32KEY)
                    else:
                        # possibly a 32bit Python on 64bit Windows, so look in
                        # the 64bit registry incase there is a 64bit app.
                        sam_flags.append(_winreg.KEY_WOW64_64KEY)
                for sam_flag in sam_flags:
                    try:
                        # assumes self.app_name is defined, as it should be for
                        # implementors
                        keyname = r"Software\Mozilla\Mozilla %s" % self.app_name
                        sam = _winreg.KEY_READ | sam_flag
                        app_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                                                  keyname, 0, sam)
                        version, _type = _winreg.QueryValueEx(
                            app_key, "CurrentVersion")
                        version_key = _winreg.OpenKey(app_key,
                                                      version + r"\Main")
                        path, _ = _winreg.QueryValueEx(version_key,
                                                       "PathToExe")
                        return path
                    except _winreg.error:
                        pass

            # search for the binary in the path
            for name in reversed(self.names):
                binary = findInPath(name)
                if sys.platform == 'cygwin':
                    program_files = os.environ['PROGRAMFILES']
                else:
                    program_files = os.environ['ProgramFiles']

                if binary is None:
                    for bin in [(program_files, 'Mozilla Firefox',
                                 'firefox.exe'),
                                (os.environ.get("ProgramFiles(x86)"),
                                 'Mozilla Firefox', 'firefox.exe'),
                                (program_files, 'Nightly', 'firefox.exe'),
                                (os.environ.get("ProgramFiles(x86)"),
                                 'Nightly', 'firefox.exe'),
                                (program_files, 'Aurora', 'firefox.exe'),
                                (os.environ.get("ProgramFiles(x86)"), 'Aurora',
                                 'firefox.exe')]:
                        path = os.path.join(*bin)
                        if os.path.isfile(path):
                            binary = path
                            break
        elif sys.platform == 'darwin':
            for bundle_name in self.bundle_names:
                # Look for the application bundle in the user's home directory
                # or the system-wide /Applications directory.  If we don't find
                # it in one of those locations, we move on to the next possible
                # bundle name.
                appdir = os.path.join("~/Applications/%s.app" % bundle_name)
                if not os.path.isdir(appdir):
                    appdir = "/Applications/%s.app" % bundle_name
                if not os.path.isdir(appdir):
                    continue

                # Look for a binary with any of the possible binary names
                # inside the application bundle.
                for binname in self.names:
                    binpath = os.path.join(appdir,
                                           "Contents/MacOS/%s-bin" % binname)
                    if (os.path.isfile(binpath)):
                        binary = binpath
                        break

                if binary:
                    break

        if binary is None:
            raise Exception(
                'Mozrunner could not locate your binary, you will need to set it.'
            )
        return binary
Beispiel #13
0
def get():
    """
  @return  [{kw}] not None
  """
    #REG = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens"

    ret = []
    import _winreg
    for (hk, path) in (
        (_winreg.HKEY_LOCAL_MACHINE, SAPI_HKLM_PATH),
        (_winreg.HKEY_CURRENT_USER, SAPI_HKCU_PATH),
    ):
        try:
            with _winreg.ConnectRegistry(None,
                                         hk) as reg:  # None = computer_name
                with _winreg.OpenKey(reg, path) as rootkey:
                    nsubkeys = _winreg.QueryInfoKey(rootkey)[0]
                    for i in xrange(nsubkeys):
                        try:
                            voicekeyname = _winreg.EnumKey(rootkey, i)
                            dprint("sapi key: %s" % voicekeyname)
                            with _winreg.OpenKey(rootkey,
                                                 voicekeyname) as voicekey:
                                clsid = _winreg.QueryValueEx(
                                    voicekey, 'CLSID')[0]
                                try:
                                    location = _winreg.QueryValueEx(
                                        voicekey, 'VoiceData')[0]
                                except WindowsError:
                                    try:
                                        location = _winreg.QueryValueEx(
                                            voicekey, 'VoicePath')[0]
                                    except WindowsError:
                                        location = ""
                                with _winreg.OpenKey(voicekey,
                                                     'Attributes') as attrkey:
                                    # ja: "411", en_US: "409:9"
                                    language = _winreg.QueryValueEx(
                                        attrkey, 'Language')[0]
                                    lcid = long(
                                        language.split(';', 1)[0], 16
                                    )  # such as '411;9' where 411 => 0x411
                                    age = _winreg.QueryValueEx(attrkey,
                                                               'Age')[0]
                                    gender = _winreg.QueryValueEx(
                                        attrkey, 'Gender')[0]
                                    name = _winreg.QueryValueEx(
                                        attrkey, 'Name')[0]
                                    vendor = _winreg.QueryValueEx(
                                        attrkey, 'Vendor')[0]
                                    uk = u(
                                        voicekeyname
                                    )  # convert to u8 using native encoding
                                    if uk:
                                        ret.append({
                                            'key':
                                            uk,
                                            'clsid':
                                            clsid,  # str
                                            'location':
                                            u(location),  # unicode
                                            'age':
                                            age,  # str
                                            #'name': u(name), # unicode
                                            'name':
                                            name,  # use str instead
                                            'vendor':
                                            u(vendor),  # unicode
                                            'lcid':
                                            lcid,  # long
                                            'language':
                                            _parselang(lcid),  #
                                            'gender':
                                            _parsegender(gender),  #
                                        })
                                    else:
                                        dwarn(
                                            "failed to convert registry key to unicode: %s"
                                            % voicekeyname)
                        except WindowsError, e:
                            dwarn(e)
                        except (ValueError, TypeError
                                ), e:  # failed to convert lcid to long
                            dwarn(e)
Beispiel #14
0
def TimeSetupStages(hive_str, state_key, product_guid, observed_code):
    """Observes setup.exe and reports about timings for each install/update stage.

  Does so by observing the registry value |observed_code| in the key at:
  |hive_str_|\|state_key|\|product_guid|.
  """
    hive = (_winreg.HKEY_LOCAL_MACHINE
            if hive_str == 'HKLM' else _winreg.HKEY_CURRENT_USER)
    key = 0
    try:
        key = _winreg.OpenKey(hive, state_key + product_guid, 0,
                              _winreg.KEY_READ)
    except WindowsError as e:
        print 'Error opening %s\\%s\\%s: %s' % (hive_str, state_key,
                                                product_guid, e)
        return

    timings = []
    start_time = 0
    saw_start = False
    current_stage = 0
    try:
        current_stage, value_type = _winreg.QueryValueEx(key, observed_code)
        assert value_type == _winreg.REG_DWORD
        print 'Starting in already ongoing stage %u' % current_stage
        start_time = time.clock()
    except WindowsError:
        print 'No ongoing stage, waiting for next install/update cycle...'

    while True:
        new_stage = 0
        try:
            new_stage, value_type = _winreg.QueryValueEx(key, observed_code)
            assert value_type == _winreg.REG_DWORD
        except WindowsError:
            # Handle the non-existant case by simply leaving |new_stage == 0|.
            pass
        if current_stage == new_stage:
            # Keep probing until a change is seen.
            time.sleep(0.01)
            continue

        if current_stage != 0:
            # Round elapsed time to 2 digits precision; anything beyond that would be
            # bogus given the above polling loop's precision.
            elapsed_time = round(time.clock() - start_time, 2)
            if saw_start:
                print '%s: Stage %u took %.2f seconds.' % (time.strftime(
                    "%x %X", time.localtime()), current_stage, elapsed_time)
                timings.append({'stage': current_stage, 'time': elapsed_time})
            else:
                print '%s: The remainder of stage %u took %.2f seconds.' % (
                    time.strftime("%x %X", time.localtime()), current_stage,
                    elapsed_time)
                # Log this timing, but mark that it was already ongoing when this script
                # started timing it.
                timings.append({
                    'stage': current_stage,
                    'time': elapsed_time,
                    'status': 'missed_start'
                })

        if new_stage != 0:
            print '%s: Starting stage %u...' % (time.strftime(
                "%x %X", time.localtime()), new_stage)
            saw_start = True
        else:
            print '%s: Install/update complete, stages timings:' % (
                time.strftime("%x %X", time.localtime()))
            print json.dumps(timings, indent=2, sort_keys=True)
            timings = []
            print '%s: No more stages, waiting for next install/update cycle...' % (
                time.strftime("%x %X", time.localtime()))

        current_stage = new_stage
        start_time = time.clock()
Beispiel #15
0
_MAX_TCP_KEEPIDLE = 300
_MAX_TCP_KEEPINTVL = 10
_MAX_TCP_KEEPCNT = 9

if sys.platform == 'win32':
    try:
        import _winreg as winreg
    except ImportError:
        import winreg

    try:
        with winreg.OpenKey(
                winreg.HKEY_LOCAL_MACHINE,
                r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters") as key:
            _DEFAULT_TCP_IDLE_MS, _ = winreg.QueryValueEx(key, "KeepAliveTime")
            _DEFAULT_TCP_INTERVAL_MS, _ = winreg.QueryValueEx(
                key, "KeepAliveInterval")
            # Make sure these are integers.
            if not isinstance(_DEFAULT_TCP_IDLE_MS, integer_types):
                raise ValueError
            if not isinstance(_DEFAULT_TCP_INTERVAL_MS, integer_types):
                raise ValueError
    except (OSError, ValueError):
        # We could not check the default values so do not attempt to override.
        def _set_keepalive_times(dummy):
            pass
    else:
        def _set_keepalive_times(sock):
            idle_ms = min(_DEFAULT_TCP_IDLE_MS, _MAX_TCP_KEEPIDLE * 1000)
            interval_ms = min(_DEFAULT_TCP_INTERVAL_MS,
Beispiel #16
0
        # http://docs.python.org/lib/module-sys.html
        # 0 (VER_PLATFORM_WIN32s)          Win32s on Windows 3.1
        # 1 (VER_PLATFORM_WIN32_WINDOWS)   Windows 95/98/ME
        # 2 (VER_PLATFORM_WIN32_NT)        Windows NT/2000/XP
        # 3 (VER_PLATFORM_WIN32_CE)        Windows CE
        if sys.getwindowsversion()[0] == 1:

            import _winreg

            try:

                # Get DirectX version from registry
                key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                                      'SOFTWARE\\Microsoft\\DirectX')
                dx_version_string = _winreg.QueryValueEx(key, 'Version')
                key.Close()

                # Set video driver to directx if DirectX 5 or better is
                # installed.
                # To interpret DirectX version numbers, see this page:
                # http://en.wikipedia.org/wiki/DirectX#Releases
                minor_dx_version = int(dx_version_string.split('.')[1])
                if minor_dx_version >= 5:
                    os.environ['SDL_VIDEODRIVER'] = 'directx'

                # Clean up namespace
                del key, dx_version_string, minor_dx_version

            except:
                pass
Beispiel #17
0
    """
    application = InVesalius(0)
    application.MainLoop()


if __name__ == '__main__':
    # Needed in win 32 exe
    if hasattr(sys,"frozen") and (sys.frozen == "windows_exe"\
                               or sys.frozen == "console_exe"):
        multiprocessing.freeze_support()

        #Click in the .inv3 file support
        root = _winreg.HKEY_CLASSES_ROOT
        key = "InVesalius 3.0\InstallationDir"
        hKey = _winreg.OpenKey(root, key, 0, _winreg.KEY_READ)
        value, type_ = _winreg.QueryValueEx(hKey, "")
        path = os.path.join(value, 'dist')

        os.chdir(path)

    # Create raycasting presets' folder, if it doens't exist
    dirpath = os.path.join(os.path.expanduser('~'), ".invesalius", "presets")
    if not os.path.isdir(dirpath):
        os.makedirs(dirpath)

    # Create logs' folder, if it doesn't exist
    dirpath = os.path.join(os.path.expanduser('~'), ".invesalius", "logs")
    if not os.path.isdir(dirpath):
        os.makedirs(dirpath)

    if hasattr(sys, "frozen") and sys.frozen == "windows_exe":
Beispiel #18
0
def GuessVisualStudioPath():
    defaultPath = r"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7" \
                  r"\IDE"
    defaultExecutable = "devenv.com"

    if not IsWindows():
        return defaultPath, defaultExecutable

    keyNamesAndExecutables = [
        # Pair for non-Express editions.
        (GetWindowsRegistryKeyName(r'Microsoft\VisualStudio'), 'devenv.com'),
        # Pair for 2012 Express edition.
        (GetWindowsRegistryKeyName(r'Microsoft\VSWinExpress'),
         'VSWinExpress.exe'),
        # Pair for pre-2012 Express editions.
        (GetWindowsRegistryKeyName(r'Microsoft\VCExpress'), 'VCExpress.exe')
    ]

    bestGuess = (0.0, (defaultPath, defaultExecutable))

    import _winreg
    for (keyName, executable) in keyNamesAndExecutables:
        try:
            key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, keyName)
        except WindowsError:
            # Can't find this key - moving on the next one.
            continue

        try:
            subkeyCounter = 0
            while True:
                try:
                    subkeyName = _winreg.EnumKey(key, subkeyCounter)
                    subkeyCounter += 1
                except WindowsError:
                    # Reached end of enumeration. Moving on the next key.
                    break

                match = re.match(r'^\d+\.\d+$', subkeyName)
                if match:
                    with _winreg.OpenKey(key, subkeyName) as subkey:
                        try:
                            (installDir, registrytype) = _winreg.QueryValueEx(
                                subkey, 'InstallDir')
                        except WindowsError:
                            # Can't find value under the key - continue to the next key.
                            continue
                        isExpress = executable != 'devenv.com'
                        if not isExpress and subkeyName == '14.0':
                            # Stop search since if we found non-Express VS2015 version
                            # installed, which is preferred version.
                            return installDir, executable
                        else:
                            version = float(subkeyName)
                            # We prefer higher version of Visual Studio and given equal
                            # version numbers we prefer non-Express edition.
                            if version > bestGuess[0]:
                                bestGuess = (version, (installDir, executable))
        finally:
            _winreg.CloseKey(key)
    return bestGuess[1]
def triage(tool_server, output_server, silent):
    """ Triage collection module """

    createt = strftime('%Y%m%d%H%M%S', gmtime())  # Timestamp in GMT
    smb_bin = tool_server + r'\tools'  # TOOLS Read-only share with third-party binary tools

    smb_data = output_server + r'\data' + r'\triage-' + os.environ[
        'COMPUTERNAME'] + r'\\' + createt  # DATA Write-only share for output data
    if not os.path.exists(r'\\' + smb_data):
        os.makedirs(r'\\' + smb_data)

    if not silent:
        print '\nSaving output to ' + r'\\' + smb_data
    """ Add your list of Sysinternal / third-party / BATCH files here """

    tool = (
        'systeminfo.cmd',  # Gathers systeminfo
        'set.cmd',  # Gathers Set variables
        'dir-tree.cmd',  # Enumerates C:\ directory tree
        'ipconfig.cmd',  # Gathers IP information
        'ip-routes.cmd',  # Gathers IP routing information
        'arp.cmd',  # Gathers ARP table information
        'dns.cmd',  # Gathers DNS Cache information
        'users.cmd',  # Gathers User/local Admin accounts
        'shares.cmd',  # Gathers local shares information
        'firewall.cmd',  # Gathers local firewall information
        'hosts.cmd',  # Captures Host file information
        'sessions.cmd',  # Gathers Active Session information
        'nbtstat.cmd',  # Gathers NetBios Sessions information
        'netstat.cmd',  # Gathers Netstat with process IDs
        'services.cmd',  # Gathers services information
        'process-list.cmd',  # Gathers WMIC Proccess list full
        'tasklist.cmd',  # Gathers Tasklist /m information
        'at-schtasks.cmd',  # Gathers scheduled tasks information
        'startup-list.cmd',  # Gathers WMIC Startup list full
        'zRemote.bat',
        'psinfo.exe /accepteula',  # Gathers basic system information
        'diskext.exe /accepteula',  # Gathers disks mounted
        'logonsessions.exe /p /accepteula',  # Gathers logon sessions and process running in them
        'psfile.exe /accepteula',  # Gathers if any files are opened remotely
        'psloggedon.exe -p /accepteula',  # Gathers all logon sessions with running processes
        'psloglist.exe -d 1 /accepteula',  # Gathers all events since in the last day
        'pslist.exe -t /accepteula',  # Gather system process tree
        'psservice.exe /accepteula',  # Gathers all the services information
        'tcpvcon.exe -a /accepteula',  # Gathers TCP/UDP connections
        'handle.exe -a -u /accepteula',  # Gathers what files are open by what processes and more
        # Gathers all DLLs not loaded in base address, unsigned and shows version information') #Runs local commands via a batch file in the tools directory.
        'listdlls.exe -r -u -v /accepteula',
        'autorunsc.exe -a * -ct -h /accepteula',  # Gathers all the autoruns service points
    )
    """ BATCH files must be called with the .bat extension """

    with open(
            r'\\' + smb_data + r'\\' + createt + '-' +
            os.environ['COMPUTERNAME'] + '-' + 'sha256-hashing.log', 'a') as g:
        for task in tool:  # Iterates over the list of commands

            fullcommand = task.split()
            commandname = fullcommand[0].split('.')

            if not silent:
                print '\nSaving output of ' + task + ' to '+r'\\'+smb_data+r'\\'+createt+'-'+os.environ['COMPUTERNAME']\
                    + '-'+commandname[0]+'.log\n'

            f = open(
                r'\\' + smb_data + r'\\' + createt + '-' +
                os.environ['COMPUTERNAME'] + '-' + commandname[0] + '.log',
                'w')

            pst = subprocess.call(r'\\' + smb_bin + r'\\' + task, stdout=f)

            g.write("%s - %s \n\n" % (f.name, hashfile(f.name)))

        guid = ""
        resul = ""
        try:
            arq = platform.architecture()
            res = arq[0]
            if (res == "32bit"):
                # x32
                hKey = _winreg.OpenKey(
                    _winreg.HKEY_LOCAL_MACHINE,
                    r"SOFTWARE\Network Associates\ePolicy Orchestrator\Agent")
                if (hKey != 0):
                    result = _winreg.QueryValueEx(hKey, "AgentGUID")
                    _winreg.CloseKey(hKey)
                    guid = result[0]
            else:
                # x64
                hKey2 = _winreg.OpenKey(
                    _winreg.HKEY_LOCAL_MACHINE,
                    r"SOFTWARE\Wow6432Node\Network Associates\ePolicy Orchestrator\Agent"
                )
                if (hKey2 != 0):
                    result = _winreg.QueryValueEx(hKey2, "AgentGUID")
                    _winreg.CloseKey(hKey2)
                    guid = result[0]

            smb_data = r'\\' + output_server + r'\data' + r'\triage-' + os.environ[
                'COMPUTERNAME'] + r'\\' + createt
            if not os.path.exists(smb_data):
                os.makedirs(smb_data)

            print '\nSaving output to ' + smb_data

            filen = createt + "-" + os.environ[
                'COMPUTERNAME'] + "-" + 'agentid.txt'
            f = sys.stdout
            sys.stdout = open(os.path.join(smb_data, filen), 'w')
            print result[0]
            sys.stdout = f

        except:
            print "Agent not installed"
            pass
Beispiel #20
0

if os.name == 'nt':  # On Windows, check out the registry to find library
    import _winreg as winreg
    regpath = r'SOFTWARE\National Instruments\NI-DAQ\CurrentVersion'
    reg6432path = r'SOFTWARE\Wow6432Node\National Instruments\NI-DAQ\CurrentVersion'
    libname = 'nidaq32'

    try:
        regkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, regpath)
    except WindowsError:
        try:
            regkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, reg6432path)
        except WindowsError:
            print('You need to install NI DAQ first.')
    nidaq_install = winreg.QueryValueEx(regkey, 'Path')[0]
    logger.info('NIDAQ install:', nidaq_install)

    lib = ctypes.util.find_library(libname)
    if lib is None:
        # try default installation path:
        lib = os.path.join(nidaq_install, r'lib\nidaq32.dll')
        if os.path.isfile(lib):
            print(
                'You should add %r to PATH environment variable and reboot.' %
                (os.path.dirname(lib)))
        else:
            lib = None
else:  # On UNIX/MAC
    # TODO: Find the location of the nidaq.h automatically (eg by using the location of the library)
    include_nidaq_h = '/usr/local/include/NIDAQmx.h'
Beispiel #21
0
    def build_win32(self):
        if not self._platforms.is_win32_active():
            return

        if not cocos.os_is_win32():
            raise cocos.CCPluginError("Please build on winodws")

        win32_projectdir = self._platforms.project_path()
        output_dir = self._output_dir

        cocos.Logging.info("building")
        # find the VS in register
        try:
            vs = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                                 r"SOFTWARE\Microsoft\VisualStudio")

        except WindowsError:
            message = "Visual Studio wasn't installed"
            raise cocos.CCPluginError(message)

        # get the solution file & project name
        cfg_obj = self._platforms.get_current_config()
        if cfg_obj.sln_file is not None:
            sln_name = cfg_obj.sln_file
            if cfg_obj.project_name is None:
                raise cocos.CCPluginError("Must specified \"%s\" when \"%s\" is specified in file \"%s\"") % \
                      (cocos_project.Win32Config.KEY_PROJECT_NAME, cocos_project.Win32Config.KEY_SLN_FILE, cocos_project.Project.CONFIG)
            else:
                name = cfg_obj.project_name
        else:
            name, sln_name = self.checkFileByExtention(".sln",
                                                       win32_projectdir)
            if not sln_name:
                message = "Can't find the \".sln\" file"
                raise cocos.CCPluginError(message)

        self.project_name = name
        projectPath = os.path.join(win32_projectdir, sln_name)

        # get the required VS version
        build_cfg_path = self._build_cfg_path()
        required_vs_version = self._get_required_vs_version(projectPath)
        if required_vs_version is None:
            raise cocos.CCPluginError(
                "Can't parse the sln file to find required VS version")

        cocos.Logging.info("Required VS version : %s" % required_vs_version)

        # get the correct available VS path
        needUpgrade = False
        vsPath = None
        i = 0
        try:
            while True:
                version = _winreg.EnumKey(vs, i)
                try:
                    if float(version) >= float(required_vs_version):
                        key = _winreg.OpenKey(vs, r"SxS\VS7")
                        vsPath, type = _winreg.QueryValueEx(key, version)

                        if float(version) > float(required_vs_version):
                            needUpgrade = True

                        break
                except:
                    pass
                i += 1
        except WindowsError:
            pass

        if vsPath is None:
            message = "Can't find correct Visual Studio's path in the regedit"
            raise cocos.CCPluginError(message)

        commandPath = os.path.join(vsPath, "Common7", "IDE", "devenv")
        build_mode = 'Debug' if self._is_debug_mode() else 'Release'

        # upgrade projects
        if needUpgrade:
            commandUpgrade = ' '.join(
                ["\"%s\"" % commandPath,
                 "\"%s\"" % projectPath, "/Upgrade"])
            self._run_cmd(commandUpgrade)

        # build the project
        commands = ' '.join([
            "\"%s\"" % commandPath,
            "\"%s\"" % projectPath,
            "/Build \"%s|Win32\"" % build_mode,
            "/Project \"%s\"" % self.project_name
        ])

        self._run_cmd(commands)

        cocos.Logging.info("build succeeded.")

        # copy files
        build_folder_name = "%s.win32" % build_mode
        build_folder_path = os.path.join(win32_projectdir, build_folder_name)
        if not os.path.isdir(build_folder_path):
            message = "Can not find the %s" % build_folder_path
            raise cocos.CCPluginError(message)

        # remove the files in output dir (keep the exe files)
        if os.path.exists(output_dir):
            output_files = os.listdir(output_dir)
            for element in output_files:
                ele_full_path = os.path.join(output_dir, element)
                if os.path.isfile(ele_full_path):
                    base_name, file_ext = os.path.splitext(element)
                    if not file_ext == ".exe":
                        os.remove(ele_full_path)
                elif os.path.isdir(ele_full_path):
                    shutil.rmtree(ele_full_path)

        # create output dir if it not existed
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)

        # copy dll & exe
        files = os.listdir(build_folder_path)
        for filename in files:
            name, ext = os.path.splitext(filename)
            proj_exe_name = "%s.exe" % self.project_name
            if ext == '.dll' or filename == proj_exe_name:
                file_path = os.path.join(build_folder_path, filename)
                cocos.Logging.info("Copying %s" % filename)
                shutil.copy(file_path, output_dir)

        # copy lua files & res
        build_cfg = os.path.join(build_cfg_path,
                                 CCPluginCompile.BUILD_CONFIG_FILE)
        if not os.path.exists(build_cfg):
            message = "%s not found" % build_cfg
            raise cocos.CCPluginError(message)
        f = open(build_cfg)
        data = json.load(f)

        if data.has_key(CCPluginCompile.CFG_KEY_MUST_COPY_RESOURCES):
            if self._no_res:
                fileList = data[CCPluginCompile.CFG_KEY_MUST_COPY_RESOURCES]
            else:
                fileList = data[CCPluginCompile.CFG_KEY_COPY_RESOURCES] + data[
                    CCPluginCompile.CFG_KEY_MUST_COPY_RESOURCES]
        else:
            fileList = data[CCPluginCompile.CFG_KEY_COPY_RESOURCES]

        for cfg in fileList:
            cocos.copy_files_with_config(cfg, build_cfg_path, output_dir)

        self.run_root = output_dir
Beispiel #22
0
def get_cpu_info_from_registry():
    '''
	FIXME: Is missing many of the newer CPU flags like sse3
	Returns the CPU info gathered from the Windows Registry. Will return None if
	not on Windows.
	'''
    global is_windows

    # Just return None if not on Windows
    if not is_windows:
        return None

    try:
        import _winreg as winreg
    except ImportError:
        import winreg

    # Get the CPU arch and bits
    key = winreg.OpenKey(
        winreg.HKEY_LOCAL_MACHINE,
        r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment")
    raw_arch_string = winreg.QueryValueEx(key, "PROCESSOR_ARCHITECTURE")[0]
    winreg.CloseKey(key)
    arch, bits = parse_arch(raw_arch_string)

    # Get the CPU MHz
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                         r"Hardware\Description\System\CentralProcessor\0")
    processor_hz = winreg.QueryValueEx(key, "~Mhz")[0]
    winreg.CloseKey(key)
    processor_hz = float(processor_hz) * 1000000.0
    processor_hz = to_friendly_hz(processor_hz)

    # Get the CPU name
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                         r"Hardware\Description\System\CentralProcessor\0")
    processor_brand = winreg.QueryValueEx(key, "ProcessorNameString")[0]
    winreg.CloseKey(key)

    # Get the CPU vendor id
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                         r"Hardware\Description\System\CentralProcessor\0")
    vendor_id = winreg.QueryValueEx(key, "VendorIdentifier")[0]
    winreg.CloseKey(key)

    # Get the CPU features
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                         r"Hardware\Description\System\CentralProcessor\0")
    feature_bits = winreg.QueryValueEx(key, "FeatureSet")[0]
    winreg.CloseKey(key)

    def is_set(bit):
        mask = 0x80000000 >> bit
        retval = mask & feature_bits > 0
        return retval

    # http://en.wikipedia.org/wiki/CPUID
    # http://unix.stackexchange.com/questions/43539/what-do-the-flags-in-proc-cpuinfo-mean
    # http://www.lohninger.com/helpcsuite/public_constants_cpuid.htm
    flags = {
        'fpu': is_set(0),  # Floating Point Unit
        'vme': is_set(1),  # V86 Mode Extensions
        'de': is_set(2),  # Debug Extensions - I/O breakpoints supported
        'pse': is_set(3),  # Page Size Extensions (4 MB pages supported)
        'tsc':
        is_set(4),  # Time Stamp Counter and RDTSC instruction are available
        'msr': is_set(5),  # Model Specific Registers
        'pae':
        is_set(6),  # Physical Address Extensions (36 bit address, 2MB pages)
        'mce': is_set(7),  # Machine Check Exception supported
        'cx8': is_set(8),  # Compare Exchange Eight Byte instruction available
        'apic':
        is_set(9),  # Local APIC present (multiprocessor operation support)
        'sepamd': is_set(10),  # Fast system calls (AMD only)
        'sep': is_set(11),  # Fast system calls
        'mtrr': is_set(12),  # Memory Type Range Registers
        'pge': is_set(13),  # Page Global Enable
        'mca': is_set(14),  # Machine Check Architecture
        'cmov': is_set(15),  # Conditional MOVe instructions
        'pat': is_set(16),  # Page Attribute Table
        'pse36': is_set(17),  # 36 bit Page Size Extensions
        'serial': is_set(18),  # Processor Serial Number
        'clflush': is_set(19),  # Cache Flush
        #'reserved1' : is_set(20), # reserved
        'dts': is_set(21),  # Debug Trace Store
        'acpi': is_set(22),  # ACPI support
        'mmx': is_set(23),  # MultiMedia Extensions
        'fxsr': is_set(24),  # FXSAVE and FXRSTOR instructions
        'sse': is_set(25),  # SSE instructions
        'sse2': is_set(26),  # SSE2 (WNI) instructions
        'ss': is_set(27),  # self snoop
        #'reserved2' : is_set(28), # reserved
        'tm': is_set(29),  # Automatic clock control
        'ia64': is_set(30),  # IA64 instructions
        '3dnow': is_set(31)  # 3DNow! instructions available
    }

    # Get a list of only the flags that are true
    flags = [k for k, v in flags.items() if v]
    flags.sort()

    return {
        'vendor_id': vendor_id,
        'brand': processor_brand,
        'hz': processor_hz,
        'arch': arch,
        'bits': bits,
        'count': multiprocessing.cpu_count(),
        'raw_arch_string': raw_arch_string,
        'l2_cache_size:': 0,
        'l2_cache_line_size': 0,
        'l2_cache_associativity': 0,
        'stepping': 0,
        'model': 0,
        'family': 0,
        'processor_type': 0,
        'extended_model': 0,
        'extended_family': 0,
        'flags': flags
    }
Beispiel #23
0
def modelsDir():
    key = winreg.OpenKey(cfg.regHead, cfg.regId + cfg.regSystemLoc, 0,
                         winreg.KEY_ALL_ACCESS)
    return winreg.QueryValueEx(key, "ModelsPath")[0]
Beispiel #24
0
def RegistryResolve():
    nameservers = []
    x = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
    try:
        y = _winreg.OpenKey(
            x, r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters")
    except EnvironmentError:  # so it isn't NT/2000/XP
        # windows ME, perhaps?
        try:  # for Windows ME
            y = _winreg.OpenKey(
                x, r"SYSTEM\CurrentControlSet\Services\VxD\MSTCP")
            nameserver, dummytype = _winreg.QueryValueEx(y, 'NameServer')
            if nameserver and not (nameserver in nameservers):
                nameservers.extend(stringdisplay(nameserver))
        except EnvironmentError:
            pass
        return nameservers  # no idea
    try:
        nameserver = _winreg.QueryValueEx(y, "DhcpNameServer")[0].split()
    except:
        nameserver = _winreg.QueryValueEx(y, "NameServer")[0].split()
    if nameserver:
        nameservers = nameserver
    nameserver = _winreg.QueryValueEx(y, "NameServer")[0]
    _winreg.CloseKey(y)
    try:  # for win2000
        y = _winreg.OpenKey(
            x,
            r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DNSRegisteredAdapters"
        )
        for i in range(1000):
            try:
                n = _winreg.EnumKey(y, i)
                z = _winreg.OpenKey(y, n)
                dnscount, dnscounttype = _winreg.QueryValueEx(
                    z, 'DNSServerAddressCount')
                dnsvalues, dnsvaluestype = _winreg.QueryValueEx(
                    z, 'DNSServerAddresses')
                nameservers.extend(binipdisplay(dnsvalues))
                _winreg.CloseKey(z)
            except EnvironmentError:
                break
        _winreg.CloseKey(y)
    except EnvironmentError:
        pass
#
    try:  # for whistler
        y = _winreg.OpenKey(
            x,
            r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces")
        for i in range(1000):
            try:
                n = _winreg.EnumKey(y, i)
                z = _winreg.OpenKey(y, n)
                try:
                    nameserver, dummytype = _winreg.QueryValueEx(
                        z, 'NameServer')
                    if nameserver and not (nameserver in nameservers):
                        nameservers.extend(stringdisplay(nameserver))
                except EnvironmentError:
                    pass
                _winreg.CloseKey(z)
            except EnvironmentError:
                break
        _winreg.CloseKey(y)
    except EnvironmentError:
        #print "Key Interfaces not found, just do nothing"
        pass


#
    _winreg.CloseKey(x)
    return nameservers
Beispiel #25
0
def isPlaying():
    # is vghd currently playing clip?
    key = winreg.OpenKey(cfg.regHead, cfg.regId + cfg.regLoc, 0,
                         winreg.KEY_ALL_ACCESS)
    res = winreg.QueryValueEx(key, "WindowPlayer")
    return res[0] == 1
Beispiel #26
0
import os, socket, win32api, _winreg

ip_addr = None
''' get ip address '''
for i in socket.getaddrinfo(socket.gethostname(), None):
    if ':' not in str(i):
        ip_addr = str(i).split('\'')[-2]
''' get currently-logged-in user '''
username = win32api.GetUserName()
''' get gw flavour name '''
try:
    install_root_reg_key = _winreg.OpenKey(
        _winreg.HKEY_LOCAL_MACHINE,
        r'SOFTWARE\Wow6432Node\Trading Technologies\Installation')
    install_root_reg_value = _winreg.QueryValueEx(install_root_reg_key,
                                                  'INSTALLROOT')
except:
    install_root_reg_key = _winreg.OpenKey(
        _winreg.HKEY_LOCAL_MACHINE,
        r'SOFTWARE\Trading Technologies\Installation')
    install_root_reg_value = _winreg.QueryValueEx(install_root_reg_key,
                                                  'INSTALLROOT')

install_path = list(install_root_reg_value)[0]

non_gw_directories = [
    'auditfiles', 'bin', 'config', 'datfiles', 'docs', 'Guardian', 'logfiles',
    'ttchron', 'ttm', 'sounds', 'x_study', 'x_trader'
]
for directory in os.listdir(install_path):
    if not any(directory_name in directory
Beispiel #27
0
def get_desktop():
    key = _winreg.OpenKey(
        _winreg.HKEY_CURRENT_USER,
        r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders',
    )
    return _winreg.QueryValueEx(key, "Desktop")[0]
Beispiel #28
0
 def create_binaries(self, py_files, extensions, dlls):
     if self.gtkdir == None:
         gtkdir = None
         # Fetchs gtk2 path from registry
         import _winreg
         import msvcrt
         try:
             k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                                 "Software\\GTK\\2.0")
         except EnvironmentError:
             raise DistutilsError(
                 'Could not find gtk+ 2.2 Runtime Environmet to copy libraries and data files.'
             )
         else:
             dir = _winreg.QueryValueEx(k, "Path")
             os.environ['PATH'] += ";%s/lib;%s/bin" % (dir[0], dir[0])
             gtkdir = dir[0]
     else:
         gtkdir = self.gtkdir
     _py2exe.create_binaries(self, py_files, extensions, dlls)
     if self.gtkdata:
         for f in find_files(gtkdir, 'lib',
                             ['*.dll.a', '*.def', '*.lib'],
                             ['pkgconfig', 'glib-2.0']):
             dest_dir = os.path.dirname(os.path.join(self.exe_dir, f))
             if not os.path.exists(dest_dir):
                 os.makedirs(dest_dir)
             self.copy_file(os.path.join(gtkdir, f),
                            os.path.join(self.exe_dir, f),
                            preserve_mode=0)
         for f in find_files(gtkdir, 'etc', ['*.*~']):
             dest_dir = os.path.dirname(os.path.join(self.exe_dir, f))
             if not os.path.exists(dest_dir):
                 os.makedirs(dest_dir)
             self.copy_file(os.path.join(gtkdir, f),
                            os.path.join(self.exe_dir, f),
                            preserve_mode=0)
         # GTK locales
         for lang in self.languages:
             glob_dir = os.path.join(gtkdir, 'share\\locale', lang,
                                     'LC_MESSAGES\\*.mo')
             for f in glob.glob(glob_dir):
                 for llang in glob.glob(
                         os.path.join(gtkdir, 'share\\locale', lang)):
                     country = os.path.basename(llang)
                     dest_dir = os.path.join(self.exe_dir,
                                             'share\\locale', country,
                                             'LC_MESSAGES')
                     if not os.path.exists(dest_dir):
                         os.makedirs(dest_dir)
                     self.copy_file(f, dest_dir)
         self.copy_file(os.path.join(gtkdir,
                                     'share\\locale\\locale.alias'),
                        os.path.join(self.exe_dir, 'share\\locale'),
                        preserve_mode=0)
         # GTK Themes
         for f in find_files(gtkdir, 'share\\themes', ['*.*~']):
             dest_dir = os.path.dirname(os.path.join(self.exe_dir, f))
             if not os.path.exists(dest_dir):
                 os.makedirs(dest_dir)
             self.copy_file(os.path.join(gtkdir, f),
                            os.path.join(self.exe_dir, f),
                            preserve_mode=0)
     if self.gtktheme != None:
         print("*** Enabling additional themes for gtk+ ***")
         for f in find_files(self.gtkthemes, 'share\\themes', ['*.*~']):
             dest_dir = os.path.dirname(os.path.join(self.exe_dir, f))
             if not os.path.exists(dest_dir):
                 os.makedirs(dest_dir)
             self.copy_file(os.path.join(self.gtkthemes, f),
                            os.path.join(self.exe_dir, f),
                            preserve_mode=0)
         for f in find_files(self.gtkthemes, 'lib\\gtk-2.0', ['*.*~']):
             dest_dir = os.path.dirname(os.path.join(self.exe_dir, f))
             if not os.path.exists(dest_dir):
                 os.makedirs(dest_dir)
             self.copy_file(os.path.join(self.gtkthemes, f),
                            os.path.join(self.exe_dir, f),
                            preserve_mode=0)
         gtktheme_dir = os.path.join(self.exe_dir, 'etc', 'gtk-2.0')
         if not os.path.exists(gtktheme_dir):
             os.makedirs(gtktheme_dir)
         file = open(os.path.join(gtktheme_dir, 'gtkrc'), 'w')
         file.write("# Generated from setup.py\n")
         file.write('gtk-theme-name = "%s"\n' % self.gtktheme)
         file.close()
     # addons
     if self.addons != None:
         print("*** Copying core addons ***")
         build = self.get_finalized_command('build')
         orig_addon_dir = os.path.join(build.build_base, self.addons)
         for f in find_files(orig_addon_dir, ''):
             dest_dir = os.path.dirname(
                 os.path.join(self.exe_dir, self.addondir, f))
             if not os.path.exists(dest_dir):
                 os.makedirs(dest_dir)
             self.copy_file(os.path.join(orig_addon_dir, f),
                            dest_dir,
                            preserve_mode=0)
Beispiel #29
0
 def get_application_path(self):
     key = winreg.OpenKey(
         winreg.HKEY_LOCAL_MACHINE,
         f'{self.REG_PATH}\\{self.app_id}',
     )
     return winreg.QueryValueEx(key, 'ApplicationPath')[0] + 'Photoshop'
Beispiel #30
0
def _find_natspeak():
    '''
    Finds engine 'natspeak.exe' path and verifies supported DNS versions via Windows Registry.
    '''

    try:
        if six.PY2:
            import _winreg as winreg
        else:
            import winreg
    except ImportError:
        printer.out("Could not import winreg")
        return ""

    printer.out("Searching Windows Registry For DNS...")
    proc_arch = os.environ['PROCESSOR_ARCHITECTURE'].lower()
    try:
        proc_arch64 = os.environ['PROCESSOR_ARCHITEW6432'].lower()
    except KeyError:
        proc_arch64 = False

    if proc_arch == 'x86' and not proc_arch64:
        arch_keys = {0}
    elif proc_arch == 'x86' or proc_arch == 'amd64':
        arch_keys = {winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY}
    else:
        raise Exception("Unhandled arch: %s" % proc_arch)

    for arch_key in arch_keys:
        key = winreg.OpenKey(
            winreg.HKEY_LOCAL_MACHINE,
            "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", 0,
            winreg.KEY_READ | arch_key)
        for i in xrange(0, winreg.QueryInfoKey(key)[0]):
            skey_name = winreg.EnumKey(key, i)
            skey = winreg.OpenKey(key, skey_name)
            DisplayName, Publisher, DisplayVersion, InstallLocation = 'null'
            try:
                DisplayName = winreg.QueryValueEx(skey, 'DisplayName')[0]
                Publisher = winreg.QueryValueEx(skey, 'Publisher')[0]
                DisplayVersion = winreg.QueryValueEx(skey, 'DisplayVersion')[0]
                InstallLocation = winreg.QueryValueEx(skey,
                                                      'InstallLocation')[0]
            except OSError as error:
                if error.errno == 2:  # Suppresses '[Error 2] The system cannot find the file specified'
                    pass
                else:
                    printer.out(error)
            finally:
                skey.Close()
                if Publisher == "Nuance Communications Inc." and "Dragon" in DisplayName:
                    DnsVersion = int(str(DisplayVersion)[:2])
                    if DnsVersion >= 13:
                        engine_path = str(
                            Path(InstallLocation).joinpath(
                                "Program/natspeak.exe"))
                        if os.path.isfile(engine_path):
                            printer.out("Search Complete.")
                            return engine_path
                    else:
                        printer.out(
                            "Dragon Naturally Speaking {} is not supported by Caster. Only versions 13 and above are supported. Purchase Dragon Naturally Speaking 13 or above"
                            .format(DnsVersion))
    printer.out("Cannot find dragon engine path")
    return ""