當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。