Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/env ruby
require 'aws/s3'
class S3Cmd
include AWS::S3
def initialize
Base.establish_connection!(
:access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'])
end
def create(args)
abort(USAGE) unless bucket = args.shift
Bucket.create(bucket)
end
def destroy(args)
abort(USAGE) unless bucket = args.shift
Bucket.delete(bucket)
end
def force_destroy(args)
abort(USAGE) unless bucket = args.shift
Bucket.delete(bucket, :force => true)
end
def buckets(args)
puts Service.buckets.map { |b| b.name }.join("\n")
end
def ls(args)
abort(USAGE) unless bucket = args.shift
puts Bucket.objects(bucket).map { |b| b.key }.join("\n")
end
def put(args)
abort(USAGE) unless fname = args.shift
abort(USAGE) unless bucket = args.shift
access = args.shift || 'private'
S3Object.store(File.basename(fname), File.read(fname), bucket, :access => access.to_sym)
puts S3Object.url_for(File.basename(fname), bucket, :authenticated => false)
end
def putnamed(args)
abort(USAGE) unless fname = args.shift
abort(USAGE) unless remote_name = args.shift
abort(USAGE) unless bucket = args.shift
access = args.shift || 'private'
S3Object.store(remote_name, File.read(fname), bucket, :access => access.to_sym)
puts S3Object.url_for(remote_name, bucket, :authenticated => false)
end
def get(args)
abort(USAGE) unless bucket = args.shift
abort(USAGE) unless fname = args.shift
url = S3Object.url_for(File.basename(fname), bucket, :authenticated => true)
system "curl -o #{fname} '#{url}'"
end
def url(args)
abort(USAGE) unless bucket = args.shift
abort(USAGE) unless fname = args.shift
puts S3Object.url_for(File.basename(fname), bucket, :authenticated => true)
end
def setperm(args)
abort(USAGE) unless bucket = args.shift
abort(USAGE) unless fname = args.shift
abort(USAGE) unless access = args.shift
end
def rm(args)
abort(USAGE) unless bucket = args.shift
abort(USAGE) unless file = args.shift
S3Object.delete(file, bucket)
end
end
USAGE = <<EOTXT
# s3 commands
buckets # list buckets
ls <bucket> # list contents of a bucket
create <bucket> # create a new bucket
destroy <bucket> # destroy bucket
force_destroy <bucket> # destroy bucket including all contents
put <file> <bucket> [<access>] # upload a file
putnamed <file> <remotename> <bucket> [<access>] # upload a file with a different name in S3
get <bucket> <file> # download a file
url <bucket> <file> # generate a temporary url
setperm <bucket> <file> <access> # set permissions (private, public_read, etc)
rm <bucket> <file> # delete a file
EOTXT
abort(USAGE) unless cmd = ARGV.shift
S3Cmd.new.send(cmd, ARGV)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.