AWS S3 存储桶复制及权限同步

曹旭辉  金牌会员 | 2024-8-23 20:04:59 | 来自手机 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 829|帖子 829|积分 2487

1、存储桶复制
分为2种: SCR , CCR 
SCR和CCR的操作文档可以参考AWS 官方文档,这里就不重复了:
复制对象 - Amazon Simple Storage Service
使用 S3 分批复制以复制现有对象 - Amazon Simple Storage Service
授予 Amazon S3 分批操作的权限 - Amazon Simple Storage Service

SCR可以同步对象的权限,不必要额外的权限同步操作。
CCR无法同步除所有者之外的权限,必要举行其他权限的同步,必要通过写批量同步权限的脚本完成同步操作
下面是同步公开READ的权限脚本示例,供参考:
  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. # Copyright WUZL. or its affiliates. All Rights Reserved.
  4. # SPDX-License-Identifier: Apache-2.0
  5. """
  6. Purpose
  7. Show how to use AWS SDK for Python (Boto3) with Amazon Simple Storage Service
  8. (Amazon S3) to perform basic object acl operations, Synchronize the public read permissions of the source and target buckets.
  9. """
  10. import json
  11. import logging
  12. # 在操作系统里需要先安全AWS boto3 SDK包 # pip3 install boto3
  13. import boto3
  14. from botocore.exceptions import ClientError
  15. logger = logging.getLogger(__name__)
  16. logger.setLevel(logging.DEBUG)
  17. # 建立一个filehandler来把日志记录在文件里,级别为debug以上
  18. fh = logging.FileHandler("boto3_s3_object_acl_modi.log")
  19. fh.setLevel(logging.DEBUG)
  20. # 建立一个streamhandler来把日志打在CMD窗口上,级别为error以上
  21. ch = logging.StreamHandler()
  22. ch.setLevel(logging.ERROR)
  23. # 设置日志格式
  24. formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(lineno)s %(message)s",datefmt="%Y-%m-%d %H:%M:%S")
  25. ch.setFormatter(formatter)
  26. fh.setFormatter(formatter)
  27. #将相应的handler添加在logger对象中
  28. logger.addHandler(ch)
  29. logger.addHandler(fh)
  30. # 开始打日志
  31. # logger.debug("debug message")
  32. # logger.info("info message")
  33. # logger.warn("warn message")
  34. # logger.error("error message")
  35. # logger.critical("critical message")
  36. # snippet-start:[python.example_code.s3.helper.ObjectWrapper]
  37. # args 变量值根据实际情况自己定义
  38. s_region_name='eu-west-2'
  39. s_aws_access_key_id='xxx'
  40. s_aws_secret_access_key='xxx'
  41. s_bucket='xxx'
  42. t_region_name='us-west-2'
  43. t_awt_accest_key_id=''
  44. t_awt_secret_accest_key='xxx'
  45. target_bucket='xxx'
  46. class ObjectWrapper:
  47.     """Encapsulates S3 object actions."""
  48.     def __init__(self, s3_object):
  49.         """
  50.         :param s3_object: A Boto3 Object resource. This is a high-level resource in Boto3
  51.                           that wraps object actions in a class-like structure.
  52.         """
  53.         self.object = s3_object
  54.         self.key = self.object.key
  55. # snippet-end:[python.example_code.s3.helper.ObjectWrapper]
  56. # snippet-start:[python.example_code.s3.GetObject]
  57.     def get(self):
  58.         """
  59.         Gets the object.
  60.         :return: The object data in bytes.
  61.         """
  62.         try:
  63.             body = self.object.get()['Body'].read()
  64.             logger.info(
  65.                 "Got object '%s' from bucket '%s'.",
  66.                 self.object.key, self.object.bucket_name)
  67.         except ClientError:
  68.             logger.exception(
  69.                 "Couldn't get object '%s' from bucket '%s'.",
  70.                 self.object.key, self.object.bucket_name)
  71.             raise
  72.         else:
  73.             return body
  74. # snippet-end:[python.example_code.s3.GetObject]
  75. # snippet-start:[python.example_code.s3.ListObjects]
  76.     @staticmethod
  77.     def list(bucket, prefix=None):
  78.         """
  79.         Lists the objects in a bucket, optionally filtered by a prefix.
  80.         :param bucket: The bucket to query. This is a Boto3 Bucket resource.
  81.         :param prefix: When specified, only objects that start with this prefix are listed.
  82.         :return: The list of objects.
  83.         """
  84.         try:
  85.             if not prefix:
  86.                 objects = list(bucket.objects.all())
  87.             else:
  88.                 objects = list(bucket.objects.filter(Prefix=prefix))
  89.             # logger.info("Got objects %s from bucket '%s'", [o.key for o in objects], bucket.name)
  90.             logger.info("Got objects from bucket '%s'", bucket.name)
  91.         except ClientError:
  92.             logger.exception("Couldn't get objects for bucket '%s'.", bucket.name)
  93.             raise
  94.         else:
  95.             return objects
  96. # snippet-end:[python.example_code.s3.ListObjects]
  97. # snippet-start:[python.example_code.s3.ListObjectsKeys]
  98.     @staticmethod
  99.     def list_all_keys(bucket, prefix=None):
  100.         """
  101.         Lists the ListObjectsKeys in a bucket, optionally filtered by a prefix.
  102.         :param bucket: The bucket to query. This is a Boto3 Bucket resource.
  103.         :param prefix: When specified, only objects that start with this prefix are listed.
  104.         :return: The list of objects.
  105.         """
  106.         try:
  107.             if not prefix:
  108.                 objects = list(bucket.objects.all())
  109.             else:
  110.                 objects = list(bucket.objects.filter(Prefix=prefix))
  111.             all_keys = [o.key for o in objects]
  112.             # logger.info("Got objects %s from bucket '%s'", [o.key for o in objects], bucket.name)
  113.             logger.info("Got objects list from bucket '%s'", bucket.name)
  114.         except ClientError:
  115.             logger.exception("Couldn't get objects for bucket '%s'.", bucket.name)
  116.             raise
  117.         else:
  118.             return all_keys
  119. # snippet-end:[python.example_code.s3.ListObjectsKeys]
  120. # snippet-start:[python.example_code.s3.GetObjectAcl]
  121.     def get_acl(self):
  122.         """
  123.         Gets the ACL of the object.
  124.         :return: The ACL of the object.
  125.         """
  126.         try:
  127.             acl = self.object.Acl()
  128.             # logger.info("Got ACL for object %s owned by %s.", self.object.key, acl.owner['DisplayName'])
  129.         except ClientError:
  130.             logger.exception("Couldn't get ACL for object %s.", self.object.key)
  131.             raise
  132.         else:
  133.             return acl
  134. # snippet-end:[python.example_code.s3.GetObjectAcl]
  135. # snippet-start:[python.example_code.s3.PutObjectAcl]
  136.     def put_acl(self, uri):
  137.         """
  138.         Applies an ACL to the object that grants read access to an AWS user identified
  139.         by email address.
  140.         :param email: The email address of the user to grant access.
  141.         """
  142.         try:
  143.             acl = self.object.Acl()
  144.             # Putting an ACL overwrites the existing ACL, so append new grants
  145.             # if you want to preserve existing grants.
  146.             grants = acl.grants if acl.grants else []
  147.             grants.append({'Grantee': {'Type': 'Group', 'URI': uri}, 'Permission': 'READ'})
  148.             acl.put(
  149.                 AccessControlPolicy={
  150.                     'Grants': grants,
  151.                     'Owner': acl.owner
  152.                 }
  153.             )
  154.             # logger.info("Granted read access to %s.", uri)
  155.         except ClientError:
  156.             logger.exception("Couldn't add ACL to object '%s'.", self.object.key)
  157.             raise
  158. # snippet-end:[python.example_code.s3.PutObjectAcl]
  159. # snippet-start:[python.example_code.s3.Scenario_ObjectManagement]
  160. def usage_demo():
  161.     # print('-'*88)
  162.     # print("Welcome to the Amazon S3 object acl modi demo!")
  163.     # print('-'*88)
  164.     # logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
  165.     # LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
  166.     # logging.basicConfig(filename='boto3_s3_object_acl_modi.log', level=logging.DEBUG, format=LOG_FORMAT)
  167.    
  168.     # s3_client = boto3.client('s3', region_name=s_region_name, aws_access_key_id=s_aws_access_key_id, aws_secret_access_key=s_aws_secret_access_key)
  169.     # response = s3_client.list_buckets()
  170.     # print('Existing buckets:')
  171.     # for bucket in response['Buckets']:
  172.     #     print(f'  {bucket["Name"]}')
  173.     s3_resource = boto3.resource('s3', region_name=s_region_name, aws_access_key_id=s_aws_access_key_id, aws_secret_access_key=s_aws_secret_access_key)
  174.     bucket = s3_resource.Bucket(s_bucket)
  175.     # print(dir(bucket))
  176.     t_s3_resource = boto3.resource('s3', region_name=t_region_name, aws_access_key_id=t_awt_accest_key_id, aws_secret_access_key=t_awt_secret_accest_key)
  177.     t_bucket = t_s3_resource.Bucket(target_bucket)
  178.     # print(dir(t_bucket))
  179.     # t_objects = ObjectWrapper.list(t_bucket)
  180.     # print(t_objects)
  181.     # prepare objects keys for modi
  182.     objects = ObjectWrapper.list(bucket)
  183.     all_keys = ObjectWrapper.list_all_keys(bucket)
  184.     # print(objects)
  185.     try:
  186.         keys=[]
  187.         len_all_keys = len(all_keys)
  188.         logger.info("len_all_keys: %s", len_all_keys)
  189.         for object_summary in objects:
  190.             len_all_keys = len_all_keys - 1
  191.             logger.info("left_keys: %s", len_all_keys)
  192.             key=str(object_summary.key)
  193.             # logger.info("object_key: '%s'", key)
  194.             # print(key+':')
  195.             object_acl = object_summary.Acl()
  196.             # print(object_acl)
  197.             # print(object_acl.grants)
  198.             # logger.info("object_grants: '%s'", str(object_acl.grants))
  199.             for grant in object_acl.grants:
  200.                 if 'READ' == grant['Permission']:
  201.                     # print('very good!')
  202.                     keys.append(key)
  203.                     break
  204.     except ClientError as error:
  205.         print(error)
  206.         
  207.     # print(keys)
  208.     logger.info("keys list len: %s", len(keys))
  209.     logger.info("source keys: %s", keys)
  210.    
  211.     logger.info("Modi target bucket object grants:")
  212.    
  213.     # prepare target objects keys for modi
  214.     t_objects = ObjectWrapper.list(t_bucket)
  215.     # print(t_objects)
  216.     # exit()
  217.     t_all_keys = ObjectWrapper.list_all_keys(t_bucket)
  218.     logger.info("t_all_keys list len: %s", len(t_all_keys))
  219.     try:
  220.         modi_keys=[]
  221.         t_keys=[]
  222.         tmp_keys = []
  223.         for tmp_key in keys:
  224.             tmp_keys.append(tmp_key)
  225.         len_left_t_keys = len(keys)
  226.         logger.info("len_left_t_keys: %s", len_left_t_keys)
  227.         for key in keys:
  228.             # logger.info("len of keys: %s, keys: %s", len(keys), keys)
  229.             len_left_t_keys = len_left_t_keys - 1
  230.             logger.info("len_left_t_keys: %s", len_left_t_keys)
  231.             if key in t_all_keys:
  232.                 t_key=key
  233.                 object_summary = t_s3_resource.ObjectSummary(target_bucket,t_key)               
  234.                 # logger.info("t_object_key: '%s'", t_key)
  235.                 # print(key+':')
  236.                 object_acl = object_summary.Acl()
  237.                 # print(object_acl)
  238.                 # print(object_acl.grants)
  239.                 # logger.info("object_grants: '%s'", str(object_acl.grants))
  240.                 # t_keys.append(t_key)
  241.                 # logger.info("len of t_keys: %s, t_keys: %s", len(t_keys), t_keys)
  242.                 for grant in object_acl.grants:
  243.                     # logger.info("grant: %s", grant)
  244.                     # if 'READ' == grant['Permission']:
  245.                     if grant['Permission'] == 'READ':
  246.                         # logger.info("object %s have permission READ", t_key)
  247.                         tmp_keys.remove(t_key)
  248.                         break
  249.                     
  250.             # logger.info("len of tmp_keys: %s, keys: %s", len(tmp_keys), tmp_keys)
  251.             modi_keys=tmp_keys
  252.         logger.info("len of modi_keys: %s ,modi_keys: '%s'", len(modi_keys), str(modi_keys))
  253.     except ClientError as error:
  254.         print(error)
  255.    
  256.     len_left_modi_keys = len(modi_keys)
  257.     for key in modi_keys:
  258.         len_left_modi_keys = len_left_modi_keys - 1
  259.         logger.info("len_left_modi_keys: %s", len_left_modi_keys)
  260.         object_key = key
  261.         # print(object_key)
  262.         obj_wrapper = ObjectWrapper(t_bucket.Object(object_key))
  263.         # print(t_bucket.Object(object_key))
  264.         object_acl = t_bucket.Object(object_key).Acl()
  265.         # print(object_acl)
  266.         # print(object_acl.grants)
  267.         try:
  268.             obj_wrapper.put_acl(uri='http://acs.amazonaws.com/groups/global/AllUsers')
  269.             acl = obj_wrapper.get_acl()
  270.             # logger.info("Put ACL grants on object '%s': '%s'", str(obj_wrapper.key), str(json.dumps(acl.grants)))
  271.             logger.info("Put ACL grants on object '%s'", str(obj_wrapper.key))
  272.         except ClientError as error:
  273.             if error.response['Error']['Code'] == 'UnresolvableGrantByEmailAddress':
  274.                 print('*'*88)
  275.                 print("This demo couldn't apply the ACL to the object because the email\n"
  276.                     "address specified as the grantee is for a test user who does not\n"
  277.                     "exist. For this request to succeed, you must replace the grantee\n"
  278.                     "email with one for an existing AWS user.")
  279.                 print('*' * 88)
  280.             else:
  281.                 raise
  282. # snippet-end:[python.example_code.s3.Scenario_ObjectManagement]
  283. if __name__ == '__main__':
  284.     usage_demo()
复制代码
代码参考:
S3 — Boto3 Docs 1.26.26 documentation
aws-doc-sdk-examples/object_wrapper.py at main · awsdocs/aws-doc-sdk-examples · GitHub

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

曹旭辉

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表