Esempio n. 1
0
 def retrieve_info(self, hkey, name_key):
     values = {}
     num = _winreg.QueryInfoKey(hkey)[1]
     for x in range(0, num):
         k = _winreg.EnumValue(hkey, x)
         if 'password' in k[0].lower():
             try:
                 password = win.Win32CryptUnprotectData(k[1][1:])
                 values[k[0]] = password.decode('utf16')
             except Exception as e:
                 print_debug('DEBUG', str(e))
                 values[k[0]] = 'N/A'
         else:
             try:
                 values[k[0]] = str(k[1]).decode('utf16')
             except Exception:
                 values[k[0]] = str(k[1])
     return values
def win32InstalledFonts(directory=None, fontext='ttf'):
    """
    Search for fonts in the specified font directory, or use the
    system directories if none given.  A list of TrueType font
    filenames are returned by default, or AFM fonts if *fontext* ==
    'afm'.
    """

    import _winreg
    if directory is None:
        directory = win32FontDirectory()

    fontext = get_fontext_synonyms(fontext)

    key, items = None, {}
    for fontdir in MSFontDirectories:
        try:
            local = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, fontdir)
        except OSError:
            continue

        if not local:
            return list_fonts(directory, fontext)
        try:
            for j in range(_winreg.QueryInfoKey(local)[1]):
                try:
                    key, direc, any = _winreg.EnumValue( local, j)
                    if not is_string_like(direc):
                        continue
                    if not os.path.dirname(direc):
                        direc = os.path.join(directory, direc)
                    direc = os.path.abspath(direc).lower()
                    if os.path.splitext(direc)[1][1:] in fontext:
                        items[direc] = 1
                except EnvironmentError:
                    continue
                except WindowsError:
                    continue
                except MemoryError:
                    continue
            return items.keys()
        finally:
            _winreg.CloseKey(local)
    return None
Esempio n. 3
0
def is_pseudo_protocal_key(input_key_name):
    key = None

    try:
        key = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, input_key_name)
    except:  #  Cannot Open This Key ..
        return False

    key_index = 0
    value_index = 0
    exist_value = False
    exist_key = False

    try:
        while True:
            value_name, value_value, value_type = _winreg.EnumValue(
                key, value_index)
            value_index += 1

            if 'URL Protocol' == value_name:
                exist_value = True
    except:
        pass

    try:
        while True:
            key_name = _winreg.EnumKey(key, key_index)
            key_index += 1

            if 'shell' == key_name:
                try:
                    pseudo_protocal_command = _winreg.OpenKey(
                        _winreg.HKEY_CLASSES_ROOT,
                        input_key_name + '\\shell\\open\\command')
                    exist_key = True
                except:
                    pass
    except:
        pass

    if exist_value and exist_key:
        return True

    return False
Esempio n. 4
0
def dump_extra_registry(hide_hardwareid):

    print("USB device(s) known by this computer :")
    print("=====================================\n")

    query = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'SYSTEM\CurrentControlSet\Enum\USBSTOR', 0)
    i = 0

    try:
        while True:
            key = _winreg.EnumKey(query, i)
            print key + "\n"
            i += 1
            query2 = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'SYSTEM\CurrentControlSet\Enum\USBSTOR' + "\\" +
                                     key, 0)
            j = 0

            try:
                while True:
                    subkey = _winreg.EnumKey(query2, j)
                    print("        " + "Serial : " + subkey + "\n")
                    j += 1
                    query3 = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'SYSTEM\CurrentControlSet\Enum\USBSTOR' +
                                             "\\" + key + "\\" + subkey, 0)
                    k = 0
                    try:
                        while True:
                            value_tuple = _winreg.EnumValue(query3, k)
                            if hide_hardwareid is True:
                                if value_tuple[0] != "HardwareID":
                                    print("        " + value_tuple[0] + " : " + str(value_tuple[1]))
                            else:
                                print("        " + value_tuple[0] + " : " + str(value_tuple[1]))
                            k += 1
                    except WindowsError, ex:
                        pass

            except WindowsError, ex:
                pass

            print("\n======================================================================\n")

    except WindowsError, ex:
        pass
Esempio n. 5
0
    def __init__(self):
        try:
            import _winreg
        except ImportError:  # Python 3
            import winreg as _winreg

        if self.info is not None:
            return
        info = []
        try:
            #XXX: Bad style to use so long `try:...except:...`. Fix it!

            prgx = re.compile(r"family\s+(?P<FML>\d+)\s+model\s+(?P<MDL>\d+)" \
                              "\s+stepping\s+(?P<STP>\d+)", re.IGNORECASE)
            chnd = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, self.pkey)
            pnum = 0
            while 1:
                try:
                    proc = _winreg.EnumKey(chnd, pnum)
                except _winreg.error:
                    break
                else:
                    pnum += 1
                    info.append({"Processor": proc})
                    phnd = _winreg.OpenKey(chnd, proc)
                    pidx = 0
                    while True:
                        try:
                            name, value, vtpe = _winreg.EnumValue(phnd, pidx)
                        except _winreg.error:
                            break
                        else:
                            pidx = pidx + 1
                            info[-1][name] = value
                            if name == "Identifier":
                                srch = prgx.search(value)
                                if srch:
                                    info[-1]["Family"] = int(srch.group("FML"))
                                    info[-1]["Model"] = int(srch.group("MDL"))
                                    info[-1]["Stepping"] = int(
                                        srch.group("STP"))
        except:
            print(sys.exc_value, '(ignoring)')
        self.__class__.info = info
Esempio n. 6
0
def list_serial_ports():
  def full_port_name(portname):
    """ Given a port-name (of the form COM7, COM12, CNCA0, etc.) returns a full
        name suitable for opening with the Serial class.
        http://eli.thegreenplace.net/2009/07/31/listing-all-serial-ports-on-windows-with-python/
    """
    m = re.match('^COM(\d+)$', portname)
    if m and int(m.group(1)) < 10:
        return portname
    return '\\\\.\\' + portname

  plat_sys = platform.system()
  plat_bits = platform.architecture()[0]

  if plat_sys == 'Windows':
    import _winreg as reg
    p = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
    k = reg.OpenKey(reg.HKEY_LOCAL_MACHINE, p)
    possible_paths = []
    i = 0
    while True:
        try:
            possible_paths.append(full_port_name(reg.EnumValue(k, i)[1]))
            i += 1
        except WindowsError:
            break
  else:
    best_candidate=None
    if plat_sys == 'Linux':
        file_prefix='ttyACM'
        if os.path.exists('/dev/arduinoZero'):
            best_candidate='/dev/arduinoZero'
      
    elif plat_sys == 'Darwin':
       file_prefix='cu.usbmodem'
    
    possible_paths = [os.path.join('/dev', x) for x in os.listdir('/dev') \
                          if x.startswith(file_prefix)]
    if best_candidate is not None:
        possible_paths.insert(0, best_candidate)

  if len(possible_paths) == 0:
    return None
  return possible_paths
Esempio n. 7
0
def findSerialPorts():
    '''
    Returns the serial ports of the motes connected to the computer.
    
    :returns: A list of tuples (name,baudrate) where:
        - name is a strings representing a serial port, e.g. 'COM1'
        - baudrate is an int representing the baurate, e.g. 115200
    '''
    serialports = []

    if os.name == 'nt':
        path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
        skip = False
        try:
            key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
        except:
            # No mote is connected
            skip = True
        if not skip:
            for i in range(winreg.QueryInfoKey(key)[1]):
                try:
                    val = winreg.EnumValue(key, i)
                except:
                    pass
                else:
                    if val[0].find('VCP') > -1:
                        serialports.append((str(val[1]), BAUDRATE_TELOSB))
                    elif val[0].find('Silabser') > -1:
                        serialports.append((str(val[1]), BAUDRATE_GINA))
                    elif val[0].find('ProlificSerial') > -1:
                        serialports.append((str(val[1]), BAUDRATE_WSN430))
    elif os.name == 'posix':
        if platform.system() == 'Darwin':
            portMask = ['/dev/tty.usbserial-*']
        else:
            portMask = ['/dev/ttyUSB*', '/dev/ttyAMA*']
        for mask in portMask:
            serialports += [(s, BAUDRATE_GINA) for s in glob.glob(mask)]

    # log
    log.info("discovered following COM port: {0}".format(
        ['{0}@{1}'.format(s[0], s[1]) for s in serialports]))

    return serialports
Esempio n. 8
0
    def __AppFirewallConfig(self, path, enableFlag, profile):
        """
        This method pokes the windows registry to enable or disable an
        application in the firewall config.
        """
        if enableFlag:
            enStr = "Enabled"
        else:
            enStr = "Disabled"

        try:
            # Get the name of the firewall applications key in the registry
            #key = "SYSTEM\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\StandardProfile\\AuthorizedApplications\\List"
            key = "SYSTEM\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\%s\\AuthorizedApplications\\List" % profile
            fwKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, key, 0,
                                    _winreg.KEY_ALL_ACCESS)

            # Get the number of applications currently configured
            (nSubKeys, nValues, lastModified) = _winreg.QueryInfoKey(fwKey)

            # Find the application among the key's values
            for i in range(0, nValues):
                (vName, vData, vType) = _winreg.EnumValue(fwKey, i)
                if path == vName:
                    # Set the flag to the value passed in
                    (p, e, d) = vData[len(vName) + 1:].split(":")
                    vData = ":".join([vName, p, enStr, d])
                    break
                else:
                    vName = None
                    vData = None

            if vName == None:
                vName = path

            if vData == None:
                vData = "%s:*:%s:AG Tools" % (path, enStr)

            # Put the value back in the registry
            _winreg.SetValueEx(fwKey, vName, 0, _winreg.REG_SZ, vData)

        except Exception:
            log.exception("Exception configuring firewall for application: %s",
                          path)
Esempio n. 9
0
def scan_serialports():
    if os.name == "nt":
        import _winreg
        ports = []
        path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
        try:
            key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path)
        except:
            return ports
        for i in range(50):
            try:
                val = _winreg.EnumValue(key, i)
                ports.append(str(val[1]))
            except:
                key.Close()
                return ports
    elif os.name == 'posix':
        #ports = glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/tty.PL*')
        return glob.glob('/dev/ttyUSB*') + glob.glob('/dev/tty.PL*')
Esempio n. 10
0
    def get_credentials(self):
        try:
            key = OpenKey(HKEY_CURRENT_USER, 'Software\\Martin Prikryl\\WinSCP 2\\Sessions')
        except Exception as e:
            self.debug(str(e))
            return False

        pwd_found = []
        num_profiles = winreg.QueryInfoKey(key)[0]
        for n in range(num_profiles):
            name_skey = winreg.EnumKey(key, n)
            skey = OpenKey(key, name_skey)
            num = winreg.QueryInfoKey(skey)[1]

            values = {}
            elements = {'HostName': 'URL', 'UserName': '******', 'PortNumber': 'Port', 'Password': '******'}
            for nn in range(num):
                k = winreg.EnumValue(skey, nn)

                for e in elements:
                    if k[0] == e:
                        if e == 'Password':
                            try:
                                values['Password'] = self.decrypt_password(
                                    username=values.get('Login', ''),
                                    hostname=values.get('URL', ''),
                                    _hash=k[1]
                                )
                            except Exception as e:
                                self.debug(str(e))
                        else:
                            values[elements[k[0]]] = str(k[1])

            if num != 0:
                if 'Port' not in values:
                    values['Port'] = '22'

                pwd_found.append(values)

            winreg.CloseKey(skey)
        winreg.CloseKey(key)

        return pwd_found
Esempio n. 11
0
def walk(top, writeable=False):
    """walk the registry starting from the key represented by
  top in the form HIVE\\key\\subkey\\..\\subkey and generating
  (key_name, key), subkey_names, values at each level.

  subkey_names are simply names of the subkeys of that key
  values are 3-tuples containing (name, data, data-type).
  See the documentation for _winreg.EnumValue for more details.
  """
    keymode = _winreg.KEY_READ
    if writeable:
        keymode |= _winreg.KEY_SET_VALUE
    if "\\" not in top: top += "\\"
    root, subkey = top.split("\\", 1)
    try:
        key = _winreg.OpenKey(getattr(_winreg, root), subkey, 0, keymode)
    except:
        key = None

    subkeys = []
    if (key):
        i = 0
        while True:
            try:
                subkeys.append(_winreg.EnumKey(key, i))
                i += 1
            except EnvironmentError:
                break

    values = []
    if (key):
        i = 0
        while True:
            try:
                values.append(_winreg.EnumValue(key, i))
                i += 1
            except EnvironmentError:
                break

    yield (top, key), subkeys, values
    for subkey in subkeys:
        for result in walk(top.rstrip("\\") + "\\" + subkey, writeable):
            yield result
Esempio n. 12
0
def get_install_lng():
    """ Return language-code used by the installer """
    lng = 0
    try:
        hive = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER)
        key = _winreg.OpenKey(hive, r"Software\SABnzbd")
        for i in range(0, _winreg.QueryInfoKey(key)[1]):
            name, value, val_type = _winreg.EnumValue(key, i)
            if name == 'Installer Language':
                lng = value
        _winreg.CloseKey(key)
    except WindowsError:
        pass
    finally:
        _winreg.CloseKey(hive)

    if lng in LanguageMap:
        return LanguageMap[lng]
    return 'en'
Esempio n. 13
0
def AllUser():

    cmd = "$AllUser = Get-WmiObject -Class Win32_UserAccount;" \
          "foreach($User in $AllUser)" \
          "{Write-Host $User.Caption};"

    cmder = "$AllUser = Get-WmiObject -Class Win32_UserAccount;" \
        "foreach($User in $AllUser)" \
        "{Write-Host $User.SID};"

    arg = [r"powershell.exe", cmd]
    ps = subprocess.Popen(arg, stdout=subprocess.PIPE)
    dc = ps.stdout.read()
    dc = dc.split('\n')

    args = [
        r"powershell.exe",
        cmder,
    ]
    p = subprocess.Popen(args, stdout=subprocess.PIPE)
    dt = p.stdout.read()
    sid = dt.split('\n')

    num = {}
    for y in range(len(dc)):
        num[dc[y]] = sid[y]

    for id in sid:
        try:
            dba = _winreg.OpenKey(_winreg.HKEY_USERS, id + "\\" + key)
            count = _winreg.QueryInfoKey(dba)[0]
            for s in range(int(count)):
                dbs = _winreg.EnumKey(dba, s)
                server = _winreg.OpenKey(_winreg.HKEY_USERS,
                                         id + os.sep + key + "\\" + dbs)
                name, value, type = _winreg.EnumValue(server, K)
                for www in num:
                    if num[www] == id:
                        # print "User:"******"SID :" + id
                        print name + ":" + value + ":" + dbs + ":" + www
        except WindowsError:
            pass
Esempio n. 14
0
File: winreg.py Progetto: moepnse/pi
    def _get_next_value(self):

        # winreg.EnumValue:
        # Enumerates values of an open registry key, returning a tuple.
        #
        # The result is a tuple of 3 items:
        # Index     Meaning
        # 0         A string that identifies the value name
        # 1         An object that holds the value data, and whose type depends on the underlying registry type
        # 2         An integer that identifies the type of the value data
        value = winreg.EnumValue(self._key_handle, self._value_index)

        value_name = value[0]
        value_data = value[1]
        value_type = value[2]

        self._value_index += 1

        return Value(self._key, self._sub_key, value_name, value_data, value_type)
Esempio n. 15
0
def serialList():
	baselist=[]
	if os.name=="nt":
		try:
			key=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"HARDWARE\\DEVICEMAP\\SERIALCOMM")
			i=0
			while(1):
				baselist+=[_winreg.EnumValue(key,i)[1]]
				i+=1
		except:
			pass
	baselist = baselist + glob.glob("/dev/ttyUSB*") + glob.glob("/dev/ttyACM*") + glob.glob("/dev/tty.usb*") + glob.glob("/dev/cu.*") + glob.glob("/dev/rfcomm*")
	prev = settings().get(["serial", "port"])
	if prev in baselist:
		baselist.remove(prev)
		baselist.insert(0, prev)
	if isDevVersion():
		baselist.append("VIRTUAL")
	return baselist
Esempio n. 16
0
def get_virtual_serial_ports():
    'Returns a list of the VCP serial ports'
    serial_ports = []
    if os.name in ['nt']:
        REGISTRY_SERIAL_PORTS = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
        key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                              REGISTRY_SERIAL_PORTS)
        for i in range(_winreg.QueryInfoKey(key)[1]):
            try:
                val = _winreg.EnumValue(key, i)
            except:
                pass
            else:
                if val[0].find('VCP') > -1:
                    serial_ports.append(str(val[1]))
    else:
        raise NotImplemented()

    return serial_ports
Esempio n. 17
0
def _read_reg_values(path, key):
    if key:
        key = path + '\\' + key
    else:
        key = path

    try:
        handle = _winreg.OpenKeyEx(_winreg.HKEY_LOCAL_MACHINE, key)
    except _winreg.error:
        return {}

    res = {}

    for i in range(_winreg.QueryInfoKey(handle)[1]):
        name, value, _ = _winreg.EnumValue(handle, i)
        res[_convert_mbcs(name)] = _convert_mbcs(value)

    _winreg.CloseKey(handle)
    return res
def get_win_registry_key(hkey_current_user_location, registry_key):
    """
    Function to retrieve a registry key value from hkey_current_user_location
    :param hkey_current_user_location: path to the key
    :param registry_key: The key you want
    :return:
    """
    LOGGER.debug('Starting get_win_registry_key')
    registry_obj = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER)

    key = _winreg.OpenKey(registry_obj, hkey_current_user_location)
    for i in range(1024):
        try:
            key_name, key_value, t = _winreg.EnumValue(key, i)
            if key_name == registry_key:
                return key_value
        except EnvironmentError:
            break
        _winreg.CloseKey(key)
Esempio n. 19
0
def list_win_serial_ports():
    serial_ports = []
    has_ports = False
    path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
    try:
        reg = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path,)
        has_ports = True
    except WindowsError:
        pass

    if has_ports:
        for i in range(128):
            try:
                name, value, type = winreg.EnumValue(reg, i)
            except WindowsError:
                pass
            else:
                serial_ports.append(value)
    return serial_ports
Esempio n. 20
0
def InfoWin32():
    import _winreg

    def GetRegistryOS(value):
        db = _winreg.OpenKey(
            _winreg.HKEY_LOCAL_MACHINE,
            'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion')

        return _winreg.QueryValueEx(db, value)[0]

    Banner('OS:')
    for key in ['ProductName', 'CSDVersion', 'CurrentBuildNumber']:
        print GetRegistryOS(key)

    Banner('CPU:')
    db = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                         'HARDWARE\\DESCRIPTION\\System\\CentralProcessor')
    for n in range(0, 1000):
        try:
            cpu = _winreg.EnumKey(db, n)
        except Exception:
            break
        print "\nProcessor :", cpu
        db_cpu = _winreg.OpenKey(db, cpu)
        for i in range(0, 1000):
            try:
                name, value, type = _winreg.EnumValue(db_cpu, i)
            except Exception:
                break
            # skip binary data
            if type == _winreg.REG_BINARY: continue
            if type == _winreg.REG_FULL_RESOURCE_DESCRIPTOR: continue
            print name, type, value

    Banner('RAM:')
    print 'TBD'
    # TODO: this is currently broken since ctypes is not available

    Banner('LOAD:')
    print 'TBD'

    Banner('UPTIME:')
    print 'TBD'
Esempio n. 21
0
def getVolume(dic_serial):
    HKLM_reg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
    path_Volume = "SOFTWARE\\Microsoft\\Windows Portable Devices\\Devices"
    key = _winreg.OpenKey(HKLM_reg, path_Volume)

    for serial in dic_serial.keys():
        i = 0
        while True:
            try:
                val_key = _winreg.EnumKey(key, i)
                if serial in val_key:
                    volumekey_path = path_Volume + "\\" + val_key
                    volumekey = _winreg.OpenKey(HKLM_reg, volumekey_path)
                    dic_serial[serial].name_volume = _winreg.EnumValue(
                        volumekey, 0)[1]
                    break
                i = i + 1
            except:
                break
Esempio n. 22
0
def GetExtensionInfo(pExtension):
    lHandle = reg.OpenKey(reg.HKEY_CLASSES_ROOT, pExtension)
    lSubKeys, lValueCount, lModified = reg.QueryInfoKey(lHandle)
    lValues = {}
    for lCount in range(0, lValueCount):
        lName, lValue, lType = reg.EnumValue(lHandle, lCount)
        if lName == '':
            lName = "File Type"
        lValues[lName] = lValue

    lKey = lValues['File Type']
    lDescription = reg.QueryValue(reg.HKEY_CLASSES_ROOT, lKey)
    lValues['Description'] = lDescription

    lKey += '\\Shell'
    lDefault = reg.QueryValue(reg.HKEY_CLASSES_ROOT, lKey)
    lValues['Default'] = lDefault

    return lValues
Esempio n. 23
0
def get_installed_runs():
    python_core = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE,
                                   "Software\\Microsoft\\Windows\\CurrentVersion\\Run")
    tuple1 = winreg.QueryInfoKey(python_core)

    list1 = []

    for i in range(tuple1[1]):
        try:
            list1.append(winreg.EnumValue(python_core, i))
        except WindowsError:
            break

    winreg.CloseKey(python_core)

    print "List for HKEY_LOCAL_MACHINE\\" + "Software\\Microsoft\\Windows\\CurrentVersion\\Run"

    for (name,value,i) in list1:
        print name, ":", value
Esempio n. 24
0
 def enumerate_tamer_ports():
     """ Uses the Win32 registry to return an
         iterator of serial (COM) ports
         existing on this computer.
     """
     path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
     try:
         key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
     except WindowsError:
         raise IterationError
 
     for i in itertools.count():
         try:
             val = winreg.EnumValue(key, i)
             print val
             if val[0].find("USBSER") != -1:
                 yield str(val[1])
         except EnvironmentError:
             break
Esempio n. 25
0
    def get_regkey(self):
        try:
            key_path = 'Software\\Skype\\ProtectedStorage'
            try:
                hkey = win.OpenKey(win.HKEY_CURRENT_USER, key_path)
            except Exception as e:
                self.debug(str(e))
                return False

            # num = winreg.QueryInfoKey(hkey)[1]
            k = winreg.EnumValue(hkey, 0)[1]
            result_bytes = win.Win32CryptUnprotectData(
                k,
                is_current_user=constant.is_current_user,
                user_dpapi=constant.user_dpapi)
            return result_bytes.decode("utf-8")
        except Exception as e:
            self.debug(str(e))
            return False
Esempio n. 26
0
def get_root_dirs():
    _root_dirs = []
    _key = None
    try:
        _sub_key = 'SYSTEM\MountedDevices'
        _key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, _sub_key)
        i = 0
        while True:
            _value, _, _ = _winreg.EnumValue(_key, i)
            if _value.startswith('\\DosDevices\\'):
                _root_dirs.append(_value[-2:])
            i += 1
    except BaseException as e:
        pass
    finally:
        if _key:
            _winreg.CloseKey(_key)

    return _root_dirs
def enumerate_serial_ports():
    if os.name == 'nt':
        """ Uses the Win32 registry to return an
        iterator of serial (COM) ports
        existing on this computer.
    """
        path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
        key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
        try:
            key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
        except WindowsError:
            raise IterationError

        for i in itertools.count():
            try:
                val = winreg.EnumValue(key, i)
                yield '\\\\.\\' + str(val[1])
            except EnvironmentError:
                break
Esempio n. 28
0
    def get_font_detail(self, font_id):
        assert font_id is not None and len(font_id.strip()) > 0

        #while not self.__font_detail_cache_lock(False):
        #    logging.warn("font cache lock acquire() has been blocked"

        font_id = font_id.strip().lower()

        if self.__font_detail_cache.get(font_id):
            #logging.debug("Font cache hit for \"%s\"" % font_id)
            return self.__font_detail_cache[font_id]

        font_info = {}
        reghandle = None
        try:
            reghandle = reg.ConnectRegistry(None, reg.HKEY_LOCAL_MACHINE)
            regkey = reg.OpenKey(reghandle, FONT_LIST_REG_KEY)
            fonts = []
            i = 0
            try:
                while True:
                    font_name, font_file, _ = reg.EnumValue(regkey, i)
                    i += 1

                    _, ext = os.path.splitext(font_file)
                    if ext.lower() != ".ttf":
                        continue

                    font_path = os.path.join(FONT_DIR, font_file)
                    if RE_BARE_FONT_NAME.match(font_name):
                        font_name = RE_BARE_FONT_NAME.match(font_name).group(1)

                    if font_name.lower() == font_id or font_file.lower(
                    ) == font_id:
                        font_info['names'] = [font_name]
                        font_info['filename'] = font_file
                        font_info['filepath'] = font_path
                        self.__font_detail_cache[font_id] = font_info
                        break
            except Exception, e:
                pass
            """
Esempio n. 29
0
def split_image(bx, by, imgFile):
    u"""[指定されたブロック数でイメージファイルを分割する]
		   bx : X方向ブロック数
		   by : Y方向ブロック数
		return: 生成されたイメージファイルリスト(ファイル名のみ)
	"""

    #分割アプリのインストール先をレジストリから取得
    try:
        reg = _winreg.OpenKey(
            _winreg.HKEY_CURRENT_USER,
            u"Software\\NSW\\イメージ分割アプリケーション".encode('ShiftJis'))
        path = _winreg.EnumValue(reg, 0)[1].encode('ShiftJis')
    except:
        path = mcmUtil.get_exe_path() + '\\'

    #分割アプリのフルパス
    exe_file = path + 'bitmapBunkatsu.exe'

    imageFile = imgFile.encode('ShiftJIS')
    exe_para = ' /mask=1,1 /output=image /image=' + imgFile.encode('ShiftJIS')
    exe_para = exe_para + ' /block={0},{1}'.format(bx, by)

    cmd = exe_file + exe_para

    #実行ファイルとパラメータをリスト化
    exe_cmd = [exe_file] + exe_para.strip().split(" ")

    try:
        #分割アプリの起動と終了待ち
        #ret = subprocess.check_call( cmd.strip().split(" ") )
        ret = subprocess.check_call(exe_cmd)
    except:
        print traceback.format_exc(sys.exc_info()[2])
        return []

    #イメージ分割で生成したファイル群の一覧を取得
    name, ext = os.path.splitext(os.path.basename(imageFile))
    out_path = os.getcwd() + '\\image\\'  #出力先はカレント\image
    files = [os.path.basename(r) for r in glob.glob(out_path + name + '*.png')]

    return files
Esempio n. 30
0
def find_serial_device_ports(try_ports=None, debug=DEBUG):
    '''
    Returns a list of all available serial ports.
    Linux: /dev/ttyUSB* or /dev/ttyACM* or /dev/*arduino*
    Mac OS X: /dev/tty.* or /dev/cu.*
    Windows: COM*
    '''
    serial_device_ports = []
    os_type = platform.system()
    if os_type == 'Linux':
        serial_device_ports = os.listdir('{0}dev'.format(os.path.sep))
        serial_device_ports = [x for x in serial_device_ports if 'ttyUSB' in x or 'ttyACM' in x or 'arduino' in x]
        serial_device_ports = ['{0}dev{0}{1}'.format(os.path.sep,x) for x in serial_device_ports]
    elif os_type == 'Windows':
        import _winreg as winreg
        import itertools

        path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
        try:
            key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
        except WindowsError:
            key = None

        if key is not None:
            for i in itertools.count():
                try:
                    val = winreg.EnumValue(key, i)
                    # Only return USBSER devices
                    if 'USBSER' in val[0]:
                        serial_device_ports.append(str(val[1]))
                except EnvironmentError:
                    break
    elif os_type == 'Darwin':
        serial_device_ports = os.listdir('{0}dev'.format(os.path.sep))
        serial_device_ports = [x for x in serial_device_ports if 'tty.' in x or 'cu.' in x]
        serial_device_ports = ['{0}dev{0}{1}'.format(os.path.sep,x) for x in serial_device_ports]

    if try_ports is not None:
        serial_device_ports = list(set(try_ports) & set(serial_device_ports))

    serial_device_ports.sort()
    return serial_device_ports