Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import boto3
- import time
- import sys
- print ("S3 Listing at %s" % time.ctime())
- s3 = boto3.client('s3');
- def listObjectsInbucket( bucketName ):
- "Displays the contents of a single bucket"
- if ( len(bucketName) == 0 ):
- print ("bucket name not provided, listing all buckets....")
- time.sleep(8)
- else:
- print ("Bucket Name provided is: %s" % bucketName)
- s3bucket = boto3.resource('s3')
- my_bucket = s3bucket.Bucket(bucketName)
- for object in my_bucket.objects.all():
- print(object.key)
- return
- def listAllBuckets():
- "Displays the contents of S3 for the current account"
- try:
- # Call S3 to list current buckets
- response = s3.list_buckets()
- for bucket in response['Buckets']:
- print (bucket['Name'])
- except ClientError as e:
- print("The bucket does not exist, choose how to deal with it or raise the exception: "+e)
- return
- def downloadObjectAsFile(BUCKET_NAME,object_key,filename):
- """
- Bucket name in the s3 bucket
- object_key ; path of the file in the bucket barring bucket name
- filename : the path of the downloaded file
- """
- try:
- s3.Bucket(BUCKET_NAME).download_file(object_key, filename)
- except botocore.exceptions.ClientError as e:
- if e.response['Error']['Code'] == "404":
- print("The object does not exist.")
- else:
- raise
- def uploadFileAsObject(BUCKET_NAME,object_key,filename):
- """
- Bucket name in the s3 bucket
- object_key ; path of the file in the bucket barring bucket name
- filename : the path of the downloaded file
- """
- try:
- s3.Bucket(BUCKET_NAME).upload_file(filename, object_key)
- except botocore.exceptions.ClientError as e:
- if e.response['Error']['Code'] == "404":
- print("The object is not created.")
- else:
- raise
- if __name__=='__main__':
- if ( len(sys.argv[1:]) != 0 ):
- showSingleBucket(''.join(sys.argv[1]))
- else:
- showAllBuckets()
Add Comment
Please, Sign In to add comment