当前位置: 首页>>代码示例>>Python>>正文


Python xattr.getxattr方法代码示例

本文整理汇总了Python中xattr.getxattr方法的典型用法代码示例。如果您正苦于以下问题:Python xattr.getxattr方法的具体用法?Python xattr.getxattr怎么用?Python xattr.getxattr使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在xattr的用法示例。


在下文中一共展示了xattr.getxattr方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_revoked

# 需要导入模块: import xattr [as 别名]
# 或者: from xattr import getxattr [as 别名]
def get_revoked(serial):
    if isinstance(serial, str):
        serial = int(serial, 16)
    path = os.path.join(config.REVOKED_DIR, "%040x.pem" % serial)
    with open(path, "rb") as fh:
        buf = fh.read()
        header, _, der_bytes = pem.unarmor(buf)
        cert = x509.Certificate.load(der_bytes)
        try:
            reason = getxattr(path, "user.revocation.reason").decode("ascii")
        except IOError: # TODO: make sure it's not required
            reason = "key_compromise"
        return path, buf, cert, \
            cert["tbs_certificate"]["validity"]["not_before"].native.replace(tzinfo=None), \
            cert["tbs_certificate"]["validity"]["not_after"].native.replace(tzinfo=None), \
            datetime.utcfromtimestamp(os.stat(path).st_ctime), \
            reason 
开发者ID:laurivosandi,项目名称:certidude,代码行数:19,代码来源:authority.py

示例2: get_attributes

# 需要导入模块: import xattr [as 别名]
# 或者: from xattr import getxattr [as 别名]
def get_attributes(cn, namespace=None, flat=False):
    path, buf, cert, signed, expires = get_signed(cn)
    attribs = dict()
    for key in listxattr(path):
        key = key.decode("ascii")
        if not key.startswith("user."):
            continue
        if namespace and not key.startswith("user.%s." % namespace):
            continue
        value = getxattr(path, key).decode("utf-8")
        if flat:
            attribs[key[len("user.%s." % namespace):]] = value
        else:
            current = attribs
            if "." in key:
                prefix, key = key.rsplit(".", 1)
                for component in prefix.split("."):
                    if component not in current:
                        current[component] = dict()
                    current = current[component]
            current[key] = value
    return path, buf, cert, attribs 
开发者ID:laurivosandi,项目名称:certidude,代码行数:24,代码来源:authority.py

示例3: on_put

# 需要导入模块: import xattr [as 别名]
# 或者: from xattr import getxattr [as 别名]
def on_put(self, req, resp, cn, tag):
        path, buf, cert, signed, expires = self.authority.get_signed(cn)
        value = req.get_param("value", required=True)
        try:
            tags = set(getxattr(path, "user.xdg.tags").decode("utf-8").split(","))
        except IOError:
            tags = set()
        try:
            tags.remove(tag)
        except KeyError:
            pass
        if "=" in tag:
            tags.add("%s=%s" % (tag.split("=")[0], value))
        else:
            tags.add(value)
        setxattr(path, "user.xdg.tags", ",".join(tags).encode("utf-8"))
        logger.info("Tag %s set to %s for %s by %s" % (tag, value, cn, req.context.get("user")))
        push.publish("tag-update", cn) 
开发者ID:laurivosandi,项目名称:certidude,代码行数:20,代码来源:tag.py

示例4: main

# 需要导入模块: import xattr [as 别名]
# 或者: from xattr import getxattr [as 别名]
def main(self):

        source_file = self.env['source_file']
        destination_file = self.env["destination_file"]
        # Check if we're trying to copy something inside a dmg.
        (dmg_path, dmg, dmg_source_path) = self.parsePathForDMG(source_file)
        try:
            if dmg:
                # Mount dmg and copy path inside.
                mount_point = self.mount(dmg_path)
                source_file = os.path.join(mount_point, dmg_source_path)
                source_file = source_file.decode("string_escape")
                destination_file = destination_file.decode("string_escape")
                xattr.listxattr(source_file)
                temp = xattr.getxattr(source_file, "com.apple.ResourceFork")
                xattr.setxattr(destination_file, "com.apple.ResourceFork", temp)
                self.output("Resource Fork copied")
        except:
            var = traceback.format_exc()
            print(("ERROR:", var))
            self.output("Resoruce Fork error: " + var)
        finally:
            if dmg:
                self.unmount(dmg_path) 
开发者ID:autopkg,项目名称:novaksam-recipes,代码行数:26,代码来源:ResourceForkCopier.py

示例5: getStoredHeaders

# 需要导入模块: import xattr [as 别名]
# 或者: from xattr import getxattr [as 别名]
def getStoredHeaders(self):
        '''Returns any stored headers for self.destination_path'''
        # try to read stored headers
        try:
            stored_plist_bytestr = xattr.getxattr(
                self.destination_path, self.GURL_XATTR)
        except (KeyError, IOError):
            return {}
        data = NSData.dataWithBytes_length_(
            stored_plist_bytestr, len(stored_plist_bytestr))
        dataObject, _plistFormat, error = (
            NSPropertyListSerialization.
            propertyListFromData_mutabilityOption_format_errorDescription_(
                data, NSPropertyListMutableContainersAndLeaves, None, None))
        if error:
            return {}
        return dataObject 
开发者ID:macadmins,项目名称:installapplications,代码行数:19,代码来源:gurl.py

示例6: get_download_link_from_xattr

# 需要导入模块: import xattr [as 别名]
# 或者: from xattr import getxattr [as 别名]
def get_download_link_from_xattr(input_path, args, facts):
    """Attempts to derive download URL from the extended attribute (xattr)
    metadata.
    """
    try:
        where_froms_string = xattr.getxattr(
            input_path, "com.apple.metadata:kMDItemWhereFroms"
        )
        where_froms = FoundationPlist.readPlistFromString(where_froms_string)
        if len(where_froms) > 0:
            facts["download_url"] = where_froms[0]
            robo_print(
                "Download URL found in file metadata: %s" % where_froms[0],
                LogLevel.VERBOSE,
                4,
            )
    except KeyError as err:
        robo_print(
            "Unable to derive a download URL from file metadata.", LogLevel.WARNING
        ) 
开发者ID:homebysix,项目名称:recipe-robot,代码行数:22,代码来源:inspect.py

示例7: target_supports_extended_attributes

# 需要导入模块: import xattr [as 别名]
# 或者: from xattr import getxattr [as 别名]
def target_supports_extended_attributes(self):
        """
        Check if the target directory supports extended filesystem
        attributes

        :return: True or False

        :rtype: bool
        """
        try:
            xattr.getxattr(self.target_dir, 'user.mime_type')
        except Exception as e:
            if format(e).startswith('[Errno 95]'):
                # libc interface [Errno 95] Operation not supported:
                return False
        return True 
开发者ID:OSInside,项目名称:kiwi,代码行数:18,代码来源:sync.py

示例8: getMacCreatorAndType

# 需要导入模块: import xattr [as 别名]
# 或者: from xattr import getxattr [as 别名]
def getMacCreatorAndType(path):
	if xattr is not None:
		try:
			finderInfo = xattr.getxattr(path, 'com.apple.FinderInfo')
		except (KeyError, IOError):
			pass
		else:
			fileType = Tag(finderInfo[:4])
			fileCreator = Tag(finderInfo[4:8])
			return fileCreator, fileType
	if MacOS is not None:
		fileCreator, fileType = MacOS.GetCreatorAndType(path)
		if sys.version_info[:2] < (2, 7) and sys.byteorder == "little":
			# work around bug in MacOS.GetCreatorAndType() on intel:
			# http://bugs.python.org/issue1594
			# (fixed with Python 2.7)
			fileCreator = _reverseString(fileCreator)
			fileType = _reverseString(fileType)
		return fileCreator, fileType
	else:
		return None, None 
开发者ID:MitchTalmadge,项目名称:Emoji-Tools,代码行数:23,代码来源:macCreatorType.py

示例9: export_crl

# 需要导入模块: import xattr [as 别名]
# 或者: from xattr import getxattr [as 别名]
def export_crl(pem=True):
    # To migrate older installations run following:
    # for j in /var/lib/certidude/*/revoked/*.pem; do echo $(attr -s 'revocation.reason' -V key_compromise $j); done
    builder = CertificateListBuilder(
        config.AUTHORITY_CRL_URL,
        certificate,
        generate_serial()
    )

    for filename in os.listdir(config.REVOKED_DIR):
        if not filename.endswith(".pem"):
            continue
        serial_number = filename[:-4]
        # TODO: Assert serial against regex
        revoked_path = os.path.join(config.REVOKED_DIR, filename)
        try:
            reason = getxattr(revoked_path, "user.revocation.reason").decode("ascii") # TODO: dedup
        except IOError: # TODO: make sure it's not required
            reason = "key_compromise"

        # TODO: Skip expired certificates
        s = os.stat(revoked_path)
        builder.add_certificate(
            int(filename[:-4], 16),
            datetime.utcfromtimestamp(s.st_ctime),
            reason)

    certificate_list = builder.build(private_key)
    if pem:
        return pem_armor_crl(certificate_list)
    return certificate_list.dump() 
开发者ID:laurivosandi,项目名称:certidude,代码行数:33,代码来源:authority.py

示例10: whitelist_subject

# 需要导入模块: import xattr [as 别名]
# 或者: from xattr import getxattr [as 别名]
def whitelist_subject(func):
    def wrapped(self, req, resp, cn, *args, **kwargs):
        from ipaddress import ip_address
        from certidude import authority
        from xattr import getxattr
        try:
            path, buf, cert, signed, expires = authority.get_signed(cn)
        except IOError:
            raise falcon.HTTPNotFound()
        else:
            # First attempt to authenticate client with certificate
            buf = req.get_header("X-SSL-CERT")
            if buf:
                header, _, der_bytes = pem.unarmor(buf.replace("\t", "").encode("ascii"))
                origin_cert = x509.Certificate.load(der_bytes)
                if origin_cert.native == cert.native:
                    logger.debug("Subject authenticated using certificates")
                    return func(self, req, resp, cn, *args, **kwargs)

            # For backwards compatibility check source IP address
            # TODO: make it disableable
            try:
                inner_address = getxattr(path, "user.lease.inner_address").decode("ascii")
            except IOError:
                raise falcon.HTTPForbidden("Forbidden", "Remote address %s not whitelisted" % req.context.get("remote_addr"))
            else:
                if req.context.get("remote_addr") != ip_address(inner_address):
                    raise falcon.HTTPForbidden("Forbidden", "Remote address %s mismatch" % req.context.get("remote_addr"))
                else:
                    return func(self, req, resp, cn, *args, **kwargs)
    return wrapped 
开发者ID:laurivosandi,项目名称:certidude,代码行数:33,代码来源:firewall.py

示例11: on_get

# 需要导入模块: import xattr [as 别名]
# 或者: from xattr import getxattr [as 别名]
def on_get(self, req, resp, cn):
        path, buf, cert, signed, expires = self.authority.get_signed(cn)
        tags = []
        try:
            for tag in getxattr(path, "user.xdg.tags").decode("utf-8").split(","):
                if "=" in tag:
                    k, v = tag.split("=", 1)
                else:
                    k, v = "other", tag
                tags.append(dict(id=tag, key=k, value=v))
        except IOError: # No user.xdg.tags attribute
            pass
        return tags 
开发者ID:laurivosandi,项目名称:certidude,代码行数:15,代码来源:tag.py

示例12: on_post

# 需要导入模块: import xattr [as 别名]
# 或者: from xattr import getxattr [as 别名]
def on_post(self, req, resp, cn):
        path, buf, cert, signed, expires = self.authority.get_signed(cn)
        key, value = req.get_param("key", required=True), req.get_param("value", required=True)
        try:
            tags = set(getxattr(path, "user.xdg.tags").decode("utf-8").split(","))
        except IOError:
            tags = set()
        if key == "other":
            tags.add(value)
        else:
            tags.add("%s=%s" % (key,value))
        setxattr(path, "user.xdg.tags", ",".join(tags).encode("utf-8"))
        logger.info("Tag %s=%s set for %s by %s" % (key, value, cn, req.context.get("user")))
        push.publish("tag-update", cn) 
开发者ID:laurivosandi,项目名称:certidude,代码行数:16,代码来源:tag.py

示例13: on_delete

# 需要导入模块: import xattr [as 别名]
# 或者: from xattr import getxattr [as 别名]
def on_delete(self, req, resp, cn, tag):
        path, buf, cert, signed, expires = self.authority.get_signed(cn)
        tags = set(getxattr(path, "user.xdg.tags").decode("utf-8").split(","))
        tags.remove(tag)
        if not tags:
            removexattr(path, "user.xdg.tags")
        else:
            setxattr(path, "user.xdg.tags", ",".join(tags))
        logger.info("Tag %s removed for %s by %s" % (tag, cn, req.context.get("user")))
        push.publish("tag-update", cn) 
开发者ID:laurivosandi,项目名称:certidude,代码行数:12,代码来源:tag.py

示例14: on_get

# 需要导入模块: import xattr [as 别名]
# 或者: from xattr import getxattr [as 别名]
def on_get(self, req, resp, cn):
        try:
            path, buf, cert, signed, expires = self.authority.get_signed(cn)
            return dict(
                last_seen =     xattr.getxattr(path, "user.lease.last_seen").decode("ascii"),
                inner_address = xattr.getxattr(path, "user.lease.inner_address").decode("ascii"),
                outer_address = xattr.getxattr(path, "user.lease.outer_address").decode("ascii")
            )
        except EnvironmentError: # Certificate or attribute not found
            raise falcon.HTTPNotFound() 
开发者ID:laurivosandi,项目名称:certidude,代码行数:12,代码来源:lease.py

示例15: on_get

# 需要导入模块: import xattr [as 别名]
# 或者: from xattr import getxattr [as 别名]
def on_get(self, req, resp, cn):

        preferred_type = req.client_prefers(("application/json", "application/x-pem-file"))
        try:
            path, buf, cert, signed, expires = self.authority.get_signed(cn)
        except EnvironmentError:
            logger.warning("Failed to serve non-existant certificate %s to %s",
                cn, req.context.get("remote_addr"))
            raise falcon.HTTPNotFound()

        if preferred_type == "application/x-pem-file":
            resp.set_header("Content-Type", "application/x-pem-file")
            resp.set_header("Content-Disposition", ("attachment; filename=%s.pem" % cn))
            resp.body = buf
            logger.debug("Served certificate %s to %s as application/x-pem-file",
                cn, req.context.get("remote_addr"))
        elif preferred_type == "application/json":
            resp.set_header("Content-Type", "application/json")
            resp.set_header("Content-Disposition", ("attachment; filename=%s.json" % cn))
            try:
                signer_username = getxattr(path, "user.signature.username").decode("ascii")
            except IOError:
                signer_username = None

            attributes = {}
            for key in listxattr(path):
                if key.startswith(b"user.machine."):
                    attributes[key[13:].decode("ascii")] = getxattr(path, key).decode("ascii")

            # TODO: dedup
            resp.body = json.dumps(dict(
                common_name = cn,
                signer = signer_username,
                serial = "%040x" % cert.serial_number,
                organizational_unit = cert.subject.native.get("organizational_unit_name"),
                signed = cert["tbs_certificate"]["validity"]["not_before"].native.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z",
                expires = cert["tbs_certificate"]["validity"]["not_after"].native.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z",
                sha256sum = hashlib.sha256(buf).hexdigest(),
                attributes = attributes or None,
                lease = None,
                extensions = dict([
                    (e["extn_id"].native, e["extn_value"].native)
                    for e in cert["tbs_certificate"]["extensions"]
                    if e["extn_id"].native in ("extended_key_usage",)])

            ))
            logger.debug("Served certificate %s to %s as application/json",
                cn, req.context.get("remote_addr"))
        else:
            logger.debug("Client did not accept application/json or application/x-pem-file")
            raise falcon.HTTPUnsupportedMediaType(
                "Client did not accept application/json or application/x-pem-file") 
开发者ID:laurivosandi,项目名称:certidude,代码行数:54,代码来源:signed.py


注:本文中的xattr.getxattr方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。