我遇到类似如何使用 s3 URL 格式将文件从自定义托管的 Minio s3 存储桶加载到 pandas 中?
但是,我已经有一个初始化的 s3 会话(来自 boto3)。我怎样才能获得从它返回的凭据以将这些直接提供给熊猫?即如何从初始化的 boto3 s3 客户端中提取 AWS_ACCESS_KEY_ID 和 AWS_SECRET_ACCESS_KEY ?
我有一个 Django 应用程序,需要使用 Boto3 创建和管理 EC2 实例。当我托管 Django 应用程序时,是否需要在服务器中安装 AWS CLI 才能在 Django 应用程序中使用 Boto3?
从 cli 我可以执行命令:\naws s3api list-objects \xe2\x80\x93-bucket BUCKETNAME -\xe2\x80\x94region REGIONAME
我如何等效地指定 的区域botocore3 list_objects_v2?
对于一些python专业人士来说,这可能是一个非常微不足道的问题,但是我使用boto3来获取一些快照信息....我在下面做了一下并得到了...我的问题是我如何得到只是" VolumeId",我认为这是一个关键值输出我可以使用一些值rs.value得到它但我没有得到所需的输出...
>>> import boto3
>>> client = boto3.client('ec2')
>>> rs = client.describe_snapshots(SnapshotIds=['snap-656f5566'])
>>> print rs
{'ResponseMetadata': {'HTTPStatusCode': 200, 'RequestId': '6f99cc31-f586-48cf-b9bd-f5ca48a536fe'}, u'Snapshots': [{u'Description': 'Created by CreateImage(i-bbe81dc1) for ami-28ne0f44 from vol-72e14126', u'Encrypted': False, u'VolumeId': 'vol-41e14536', u'State': 'completed', u'VolumeSize': 30, u'Progress': '100%', u'StartTime': datetime.datetime(2012, 10, 7, 14, 33, 16, tzinfo=tzlocal()), u'SnapshotId': 'snap-658f5566', u'OwnerId': '0111233286342'}]}
>>>
>>>
>>> dir(rs)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', …Run Code Online (Sandbox Code Playgroud) 我是boto3的新手,并且正在使用它来自动注册和从负载均衡器注销EC2实例的过程.
这是我的示例Python代码:
import boto3
elbList = boto3.client('elb')
bals = elbList.describe_load_balancers()
for elb in bals['LoadBalancerDescriptions']:
print 'ELB Name:' + elb['LoadBalancerName'] + 'ELB scheme type: ' + elb['Scheme']
Run Code Online (Sandbox Code Playgroud)
此脚本仅列出我的所有经典负载均衡器,但未列出我的应用程序负载均衡器.
如何列出我的应用程序负载均衡器并列出附加到它的所有实例?
我正在使用AWS的Boto3编写一个Python脚本来管理安全组.我创建了一个字典来获取组ID及其属性.我可以访问属性,sg-aaaaaaaa但当我试图访问时sg-bbbbbbbb,它总是抛出一个KeyError.
def get_rules(sg_ids, region):
sg_rules = {}
sg_rules['SecurityGroups'] = []
ec2 = boto3.client('ec2', region_name=region)
for sg_id in sg_ids:
response = ec2.describe_security_groups(
Filters=[
{
'Name': 'group-id',
'Values': [
sg_id
]
}
]
)
data = response['SecurityGroups'][0]['IpPermissions']
sg_rules['SecurityGroups'].append({sg_id: data})
return sg_rules
Run Code Online (Sandbox Code Playgroud)
{'SecurityGroups': [{'sg-aaaaaaaa': [{'FromPort': 22, 'IpProtocol': 'tcp', 'IpRanges': [{'CidrIp': 'XX.XX.XX.XX/32'}], 'Ipv6Ranges': [], 'PrefixListIds': [], 'ToPort': 22, 'U
serIdGroupPairs': []}, {'FromPort': 6556, 'IpProtocol': 'tcp', 'IpRanges': [{'CidrIp': 'XX.XX.XX.XX/32'}], 'Ipv6Ranges': [], 'PrefixListIds': [], 'ToPort': 6556, 'UserIdGroup
Pairs': …Run Code Online (Sandbox Code Playgroud) 我正在尝试将AWS的SNS与SSM一起使用,但却收到有关角色的错误.
这是错误:
botocore.errorfactory.InvalidRole: An error occurred (InvalidRole) when calling the SendCommand operation: ServiceRoleArn is not valid: arn:aws:iam::<account #>:role/FullSNS
Run Code Online (Sandbox Code Playgroud)
这是相关的代码:
response = client.send_command(
InstanceIds=[
'<instance id>',
],
DocumentName='AWS-RunShellScript',
Parameters={
'commands': [
'<command>',
],
'workingDirectory': [
'<directory>'
]
},
OutputS3BucketName='<s3 bucket>',
ServiceRoleArn='arn:aws:iam::<account #>:role/FullSNS',
NotificationConfig={
'NotificationArn': 'arn:aws:sns:us-east-1:<account #>:MyTestTopic',
'NotificationEvents': [
'All',
],
'NotificationType': 'Command'
}
)
Run Code Online (Sandbox Code Playgroud)
以下是该角色的政策:
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"sns:*"
],
"Effect": "Allow",
"Resource": "*"
}
]
}
Run Code Online (Sandbox Code Playgroud)
以上是与boto3,但如果我在控制台中尝试它我会得到相同的错误.
以下代码用于发送消息,但是当它到达时,它会显示发件人ID的文本"VERIFY".如何指定发件人ID?我认为这是使用消息属性完成的,但我无法弄清楚语法.
session = boto3.session.Session(profile_name='Credentials',region_name='us-east-1')
theMessage='Now is the time for all good people to come to the aid of their party'
senderID='Godzilla'
snsclient = session.client('sns')
response = snsclient.publish(PhoneNumber='+84932575571', Message=theMessage)
pp = pprint.PrettyPrinter(indent=4)
print(pp.pprint(response))
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用以下代码,但无法使其正常工作。即使我完全按照文档中的说明进行操作,也会不断给我关于过滤器表达式类型错误的错误消息。我该怎么做才能解决此问题?
def EndpointDeleted(event):
endpoint = event['Attributes']['EndpointArn']
if('EndpointArn' in event['Attributes']):
client = boto3.client('dynamodb')
response = client.scan(
TableName='sniffergps-mobilehub-812282467-Users',
Select='ALL_ATTRIBUTES',
FilterExpression=Attr('Endpoints').contains(endpoint)
)
return responseRun Code Online (Sandbox Code Playgroud)
但是我收到一个错误消息,说过滤器表达式是错误的类型。我有以下导入消息:
import boto3
from boto3.dynamodb.conditions import Key
from boto3.dynamodb.conditions import Attr
错误信息:
{
"errorMessage": "Parameter validation failed:\nInvalid type for parameter FilterExpression, value: <boto3.dynamodb.conditions.Contains object at 0x7fdca25e0b38>, type: <class 'boto3.dynamodb.conditions.Contains'>, valid types: <class 'str'>",
"errorType": "ParamValidationError",
"stackTrace": [
[
"/var/task/lambda_function.py",
13,
"lambda_handler",
"return EndpointDeleted(event)"
],
[
"/var/task/lambda_function.py",
24,
"EndpointDeleted",
"FilterExpression=Attr('Endpoints').contains(endpoint)"
],
[
"/var/runtime/botocore/client.py",
312,
"_api_call",
"return …Run Code Online (Sandbox Code Playgroud)下面的代码工作正常,除非有一个子文件夹,里面没有任何文件,那么子文件夹将不会出现在S3中.例如,如果/ home/temp/subfolder没有文件,那么子文件夹将不会显示在S3中.如何更改代码以便在S3中也上传空文件夹?我试着写... (请参阅下面的注释),但不知道如何将put_object()调用到空子文件夹.
#!/usr/bin/env python
import os
from boto3.session import Session
path = "/home/temp"
session = Session(aws_access_key_id='XXX', aws_secret_access_key='XXX')
s3 = session.resource('s3')
for subdir, dirs, files in os.walk(path):
# note: if not files ......
for file in files:
full_path = os.path.join(subdir, file)
with open(full_path, 'rb') as data:
s3.Bucket('my_bucket').put_object(Key=full_path[len(path)+1:],
Body=data)
Run Code Online (Sandbox Code Playgroud)
此外,我试图调用此函数来检查子文件夹或文件是否存在.它适用于文件,但不适用于子文件夹.如何检查子文件夹是否存在?(如果存在子文件夹,我将不会上传)
def check_exist(s3, bucket, key):
try:
s3.Object(bucket, key).load()
except botocore.exceptions.ClientError as e:
return False
return True
Run Code Online (Sandbox Code Playgroud)
顺便说一下,我参考上面的代码
和
http://www.developerfiles.com/upload-files-to-s3-with-python-keeping-the-original-folder-structure/
感谢他们分享代码.
boto3 ×10
python ×5
amazon-s3 ×2
amazon-sns ×2
amazon-ec2 ×1
amazon-elb ×1
amazon-iam ×1
aws-cli ×1
aws-lambda ×1
aws-sdk ×1
boto ×1
dictionary ×1
django ×1
python-2.7 ×1
python-3.x ×1
ssm ×1