Guest User

Untitled

a guest
Dec 13th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. import boto3
  2. import time
  3. import sys
  4.  
  5. print ("S3 Listing at %s" % time.ctime())
  6. s3 = boto3.client('s3');
  7.  
  8. def listObjectsInbucket( bucketName ):
  9. "Displays the contents of a single bucket"
  10. if ( len(bucketName) == 0 ):
  11. print ("bucket name not provided, listing all buckets....")
  12. time.sleep(8)
  13. else:
  14. print ("Bucket Name provided is: %s" % bucketName)
  15. s3bucket = boto3.resource('s3')
  16. my_bucket = s3bucket.Bucket(bucketName)
  17. for object in my_bucket.objects.all():
  18. print(object.key)
  19. return
  20.  
  21. def listAllBuckets():
  22. "Displays the contents of S3 for the current account"
  23. try:
  24. # Call S3 to list current buckets
  25. response = s3.list_buckets()
  26. for bucket in response['Buckets']:
  27. print (bucket['Name'])
  28. except ClientError as e:
  29. print("The bucket does not exist, choose how to deal with it or raise the exception: "+e)
  30. return
  31.  
  32. def downloadObjectAsFile(BUCKET_NAME,object_key,filename):
  33. """
  34. Bucket name in the s3 bucket
  35. object_key ; path of the file in the bucket barring bucket name
  36. filename : the path of the downloaded file
  37. """
  38. try:
  39. s3.Bucket(BUCKET_NAME).download_file(object_key, filename)
  40. except botocore.exceptions.ClientError as e:
  41. if e.response['Error']['Code'] == "404":
  42. print("The object does not exist.")
  43. else:
  44. raise
  45.  
  46. def uploadFileAsObject(BUCKET_NAME,object_key,filename):
  47. """
  48. Bucket name in the s3 bucket
  49. object_key ; path of the file in the bucket barring bucket name
  50. filename : the path of the downloaded file
  51. """
  52. try:
  53. s3.Bucket(BUCKET_NAME).upload_file(filename, object_key)
  54. except botocore.exceptions.ClientError as e:
  55. if e.response['Error']['Code'] == "404":
  56. print("The object is not created.")
  57. else:
  58. raise
  59.  
  60. if __name__=='__main__':
  61. if ( len(sys.argv[1:]) != 0 ):
  62. showSingleBucket(''.join(sys.argv[1]))
  63. else:
  64. showAllBuckets()
Add Comment
Please, Sign In to add comment