通过Python的SDK连接aws
aws上生成访问密钥 ID 和私有访问密钥
1.Windows连接方式:
1 . 通过Windows连接到 aws服务器时,需要通过“访问密钥(访问密钥 ID 和私有访问密钥)”
2 . 需要在C:\Users\admin\.aws中创建credentials文件(.aws目录不存在需要手动创建admin为你当前系统用户家目录)
cat /c/Users/admin/.aws/credentials
[default]
aws_access_key_id = xxxxxxxxxxxxxxxxxxxxxxx
aws_secret_access_key = xxxxxxxxxxxxxxxxxxxxxxxxxxxx
3 . 安装boto3模块
pip install boto3
4 . 列出已经存在的s3存储桶
import boto3
s3client = boto3.client("s3")
for bucket in s3client.list_buckets()["Buckets"]:
print(bucket)
输出:
{'Name': 'xxxxxxs3', 'CreationDate': datetime.datetime(2017, 8, 2, 4, 16, 31, tzinfo=tzutc())}
{'Name': 'testxxxxxs3', 'CreationDate': datetime.datetime(2017, 8, 2, 6, 57, 29, tzinfo=tzutc())}
2.Linux连接方式:
1 . 安装boto3模块
pip install boto3
2 . 创建.aws目录
[ec2-user@LiBaolin-Singapore#>> ~]$mkdir .aws
3 . 创建credentials文件
[ec2-user@LiBaolin-Singapore#>> ~/.aws]$cat credentials
[default]
aws_access_key_id = xxxxxxxxxxxxxxxxxxxxxxx
aws_secret_access_key = xxxxxxxxxxxxxxxxxxxxxxxxxxxx
4 . clone一个测试实例
[ec2-user@LiBaolin-Singapore#>> ~]$git clone https://github.com/awslabs/aws-python-sample.git
5 . 运行测试实例(会创建一个存储桶,并创建一个文件,最后删除该存储桶)
[ec2-user@LiBaolin-Singapore#>> ~/aws-python-sample]$python s3_sample.py
6 . s3_sample.py代码如下:
import boto3
import uuid
s3client = boto3.client('s3')
bucket_name = 'python-sdk-sample-{}'.format(uuid.uuid4())
print('Creating new bucket with name: {}'.format(bucket_name))
s3client.create_bucket(Bucket=bucket_name)
list_buckets_resp = s3client.list_buckets()
for bucket in list_buckets_resp['Buckets']:
if bucket['Name'] == bucket_name:
print('(Just created) --> {} - there since {}'.format(
bucket['Name'], bucket['CreationDate']))
object_key = 'python_sample_key.txt'
print('Uploading some data to {} with key: {}'.format(
bucket_name, object_key))
s3client.put_object(Bucket=bucket_name, Key=object_key, Body=b'Hello World!')
url = s3client.generate_presigned_url(
'get_object', {'Bucket': bucket_name, 'Key': object_key})
print('\nTry this URL in your browser to download the object:')
print(url)
input("\nPress enter to continue...")
print('\nNow using Resource API')
s3resource = boto3.resource('s3')
bucket = s3resource.Bucket(bucket_name)
obj = bucket.Object(object_key)
print('Bucket name: {}'.format(bucket.name))
print('Object key: {}'.format(obj.key))
print('Object content length: {}'.format(obj.content_length))
print('Object body: {}'.format(obj.get()['Body'].read()))
print('Object last modified: {}'.format(obj.last_modified))
print('\nDeleting all objects in bucket {}.'.format(bucket_name))
## 以下部分为 删除刚才创建的存储桶,为了看到效果可以先注释,而后在手动删除
delete_responses = bucket.objects.delete()
for delete_response in delete_responses:
for deleted in delete_response['Deleted']:
print('\t Deleted: {}'.format(deleted['Key']))
print('\nDeleting the bucket.')
bucket.delete()