Searching S3 Buckets for an Object

I wrote this code for a project that I was working on for a client. The goal was to look in an S3 bucket to find objects that match a specific identification number. Specifically, they are looking to return audio logs from calls in an AWS Connect instance.

In this script, we are utilizing Boto3 to iterate through objects in a provided S3 bucket and then returning the object keys. The keys are passed to a function that will generate a pre-signed URL for the user to utilize for downloading the object.

import os
import sys
import boto3
import logging
from botocore.exceptions import ClientError

# USAGE: python3 main.py <item you want>
object_to_find = sys.argv[1]
bucket = "Your bucket name"

s3 = boto3.client('s3')
def get_objects(object_to_find):
    links = []
    response = s3.list_objects_v2(
        Bucket=bucket,
    )
    for x in response['Contents']:
        if object_to_find in x['Key']:
            links.append(x['Key'])
    return links

def create_presigned_url(bucket_name, object_name, expiration=3600):
    s3_client = boto3.client('s3')
    try:
        s3 = boto3.resource('s3')
        s3.Object(bucket_name, object_name).load()
    except ClientError as e:
        if e.response['Error']['Code'] == '404':
            return "Object doesn't exist " + object_name
    try:
        response = s3_client.generate_presigned_url('get_object',
            Params={'Bucket': bucket_name, 
                    'Key': object_name},
            ExpiresIn=expiration
            )
    except ClientError as e:
        print(e)
        return None
    return response
links = get_objects(object_to_find)
for x in links:
    print(create_presigned_url(bucket, x, expiration=3600))

Test it out and let me know if you find it helpful!


Posted

in

,

by

Tags:

Comments

Leave a Reply