当前位置: 首页>>代码示例>>Python>>正文


Python boto3.client方法代码示例

本文整理汇总了Python中boto3.client方法的典型用法代码示例。如果您正苦于以下问题:Python boto3.client方法的具体用法?Python boto3.client怎么用?Python boto3.client使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在boto3的用法示例。


在下文中一共展示了boto3.client方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_settings

# 需要导入模块: import boto3 [as 别名]
# 或者: from boto3 import client [as 别名]
def get_settings(self):
        """Return the DynamoDB aws-auto-remediate-settings table in a Python dict format
        
        Returns:
            dict -- aws-auto-remediate-settings table
        """
        settings = {}
        try:
            for record in boto3.client("dynamodb").scan(
                TableName=os.environ["SETTINGSTABLE"]
            )["Items"]:
                record_json = dynamodb_json.loads(record, True)
                settings[record_json["key"]] = record_json["value"]
        except:
            self.logging.error(
                f"Could not read DynamoDB table '{os.environ['SETTINGSTABLE']}'."
            )
            self.logging.error(sys.exc_info()[1])

        return settings 
开发者ID:servian,项目名称:aws-auto-remediate,代码行数:22,代码来源:lambda_handler.py

示例2: _schedule_function

# 需要导入模块: import boto3 [as 别名]
# 或者: from boto3 import client [as 别名]
def _schedule_function(self, function_arn, schedule):
        LOGGER.info('Scheduling function {} to {}'.format(self._function_name, schedule))
        events_client = boto.client('events')
        trigger_name = '{}-trigger'.format(self._function_name)

        rule_response = events_client.put_rule(
            Name=trigger_name,
            ScheduleExpression=schedule,
            State='ENABLED',
        )
        self._lambda_client.add_permission(
            FunctionName=self._function_name,
            StatementId="{0}-Event".format(trigger_name),
            Action='lambda:InvokeFunction',
            Principal='events.amazonaws.com',
            SourceArn=rule_response['RuleArn'],
        )
        events_client.put_targets(
            Rule=trigger_name,
            Targets=[{'Id': "1", 'Arn': function_arn}]
        ) 
开发者ID:ellimilial,项目名称:sqs-s3-logger,代码行数:23,代码来源:environment.py

示例3: get_kms_auth_token

# 需要导入模块: import boto3 [as 别名]
# 或者: from boto3 import client [as 别名]
def get_kms_auth_token(session, bless_config, lambda_regional_config):
    logger.info("Requesting new KMS auth token in %s", lambda_regional_config["aws_region"])
    token_not_before = datetime.datetime.utcnow() - datetime.timedelta(minutes=1)
    token_not_after = token_not_before + datetime.timedelta(hours=1)
    token = dict(not_before=token_not_before.strftime("%Y%m%dT%H%M%SZ"),
                 not_after=token_not_after.strftime("%Y%m%dT%H%M%SZ"))
    encryption_context = {
        "from": session.resource("iam").CurrentUser().user_name,
        "to": bless_config["lambda_config"]["function_name"],
        "user_type": "user"
    }
    kms = session.client('kms', region_name=lambda_regional_config["aws_region"])
    res = kms.encrypt(KeyId=lambda_regional_config["kms_auth_key_id"],
                      Plaintext=json.dumps(token),
                      EncryptionContext=encryption_context)
    return base64.b64encode(res["CiphertextBlob"]).decode() 
开发者ID:kislyuk,项目名称:aegea,代码行数:18,代码来源:ssh.py

示例4: describe_services

# 需要导入模块: import boto3 [as 别名]
# 或者: from boto3 import client [as 别名]
def describe_services():
    client = boto3.client("pricing", region_name="us-east-1")
    return paginate(client.get_paginator("describe_services")) 
开发者ID:kislyuk,项目名称:aegea,代码行数:5,代码来源:pricing.py

示例5: lambda_handler

# 需要导入模块: import boto3 [as 别名]
# 或者: from boto3 import client [as 别名]
def lambda_handler(event, context):
    print(event)
    slingSG_List = []
    optintag = ""
    if "TagName" in event:
        optintag = event['TagName']
        slingSG_List = getSGList(optintag)
        if len(slingSG_List) >= 1:
            sgidnum = changeR(slingSG_List)
            PortChange = addport(sgidnum)
            Package = json.dumps(PortChange)
            print(sgidnum + ' selected for slinging.')
            print(Package)
            response = client.invoke(
                FunctionName='PortChange_Slingr',
                InvocationType='Event',
                Payload=Package
            )
        else:
            print('No security groups with opt-in tags found.  Doing nothing.')
    else:
        print("No opt-in tag specified.  Doing nothing.")
    #getSecGroupIPPermissions(sgidnum) 
开发者ID:Optum,项目名称:ChaoSlingr,代码行数:25,代码来源:PortChange_Generatr.py

示例6: __init__

# 需要导入模块: import boto3 [as 别名]
# 或者: from boto3 import client [as 别名]
def __init__(self, arguments: argparse.Namespace, help_text: str):
        self.profile_name = arguments.profile_name
        self.access_key = arguments.access_key
        self.secret_access_key = arguments.secret_access_key
        self.session_token = arguments.session_token
        self.region = arguments.region
        self.command = arguments.command
        self.api_id = arguments.api_id
        self.url = arguments.url
        self.api_list = []
        self.client = None
        self.help = help_text

        if self.access_key and self.secret_access_key:
            if not self.region:
                self.error('Please provide a region with AWS credentials')

        if not self.load_creds():
            self.error('Unable to load AWS credentials')

        if not self.command:
            self.error('Please provide a valid command') 
开发者ID:ustayready,项目名称:fireprox,代码行数:24,代码来源:fire.py

示例7: _try_instance_profile

# 需要导入模块: import boto3 [as 别名]
# 或者: from boto3 import client [as 别名]
def _try_instance_profile(self) -> bool:
        """Try instance profile credentials

        :return:
        """
        try:
            if not self.region:
                self.client = boto3.client('apigateway')
            else:
                self.client = boto3.client(
                    'apigateway',
                    region_name=self.region
                )
            self.client.get_account()
            self.region = self.client._client_config.region_name
            return True
        except:
            return False 
开发者ID:ustayready,项目名称:fireprox,代码行数:20,代码来源:fire.py

示例8: create_api

# 需要导入模块: import boto3 [as 别名]
# 或者: from boto3 import client [as 别名]
def create_api(self, url):
        if not url:
            self.error('Please provide a valid URL end-point')

        print(f'Creating => {url}...')

        template = self.get_template()
        response = self.client.import_rest_api(
            parameters={
                'endpointConfigurationTypes': 'REGIONAL'
            },
            body=template
        )
        resource_id, proxy_url = self.create_deployment(response['id'])
        self.store_api(
            response['id'],
            response['name'],
            response['createdDate'],
            response['version'],
            url,
            resource_id,
            proxy_url
        ) 
开发者ID:ustayready,项目名称:fireprox,代码行数:25,代码来源:fire.py

示例9: update_api

# 需要导入模块: import boto3 [as 别名]
# 或者: from boto3 import client [as 别名]
def update_api(self, api_id, url):
        if not any([api_id, url]):
            self.error('Please provide a valid API ID and URL end-point')

        if url[-1] == '/':
            url = url[:-1]

        resource_id = self.get_resource(api_id)
        if resource_id:
            print(f'Found resource {resource_id} for {api_id}!')
            response = self.client.update_integration(
                restApiId=api_id,
                resourceId=resource_id,
                httpMethod='ANY',
                patchOperations=[
                    {
                        'op': 'replace',
                        'path': '/uri',
                        'value': '{}/{}'.format(url, r'{proxy}'),
                    },
                ]
            )
            return response['uri'].replace('/{proxy}', '') == url
        else:
            self.error(f'Unable to update, no valid resource for {api_id}') 
开发者ID:ustayready,项目名称:fireprox,代码行数:27,代码来源:fire.py

示例10: send_to_missing_remediation_topic

# 需要导入模块: import boto3 [as 别名]
# 或者: from boto3 import client [as 别名]
def send_to_missing_remediation_topic(self, config_rule_name, config_payload):
        """Publishes a message onto the missing remediation SNS Topic. The topic should be subscribed to
        by administrators to be aware when their security remediations are not fully covered.
        
        Arguments:
            config_rule_name {string} -- AWS Config Rule name
            config_payload {dictionary} -- AWS Config Rule payload
        """
        client = boto3.client("sns")
        topic_arn = os.environ["MISSINGREMEDIATIONTOPIC"]

        try:
            client.publish(
                TopicArn=topic_arn,
                Message=json.dumps(config_payload),
                Subject=f"No remediation available for Config Rule '{config_rule_name}'",
            )
        except:
            self.logging.error(f"Could not publish to SNS Topic 'topic_arn'.") 
开发者ID:servian,项目名称:aws-auto-remediate,代码行数:21,代码来源:lambda_handler.py

示例11: write_output

# 需要导入模块: import boto3 [as 别名]
# 或者: from boto3 import client [as 别名]
def write_output(bucket_name, key_name, output_key_name, outstanding_requesters):
    logging.getLogger().debug('[write_output] Start')

    try:
        current_data = '/tmp/' + key_name.split('/')[-1] + '_LOCAL.json'
        with open(current_data, 'w') as outfile:
            json.dump(outstanding_requesters, outfile)

        s3 = boto3.client('s3')
        s3.upload_file(current_data, bucket_name, output_key_name, ExtraArgs={'ContentType': "application/json"})
        remove(current_data)

    except Exception as e:
        logging.getLogger().error("[write_output] \tError to write output file")
        logging.getLogger().error(e)

    logging.getLogger().debug('[write_output] End') 
开发者ID:awslabs,项目名称:aws-waf-security-automations,代码行数:19,代码来源:log-parser.py

示例12: create_ami

# 需要导入模块: import boto3 [as 别名]
# 或者: from boto3 import client [as 别名]
def create_ami(instance_id, image_params):
    client = boto3.client('ec2')
    # stop the instance so we don't get charged for the template instance running time after the AMI is created
    client.stop_instances(InstanceIds=[instance_id])
    waiter = client.get_waiter('instance_stopped')
    waiter.wait(InstanceIds=[instance_id])

    for forbidden_param in ['InstanceId', 'NoReboot', 'DryRun']:
        if forbidden_param in image_params:
            del image_params[forbidden_param]

    response = client.create_image(
        InstanceId=instance_id,
        **image_params
    )

    ami_id = response['ImageId']

    return ami_id 
开发者ID:PokaInc,项目名称:cloudformation-ami,代码行数:21,代码来源:ami.py

示例13: status_is_ok

# 需要导入模块: import boto3 [as 别名]
# 或者: from boto3 import client [as 别名]
def status_is_ok(instance_id):
    response = boto3.client('ec2').describe_instance_status(
        InstanceIds=[
            instance_id,
        ]
    )

    print('status response:', response)

    instance_statuses = response['InstanceStatuses']
    instance_statuses = list(filter(lambda s: s['InstanceId'] == instance_id, instance_statuses))
    assert len(instance_statuses) <= 1

    if not instance_statuses:
        return False

    instance_status = instance_statuses[0]

    return instance_status['InstanceStatus']['Status'] == 'ok' and instance_status['SystemStatus']['Status'] == 'ok' 
开发者ID:PokaInc,项目名称:cloudformation-ami,代码行数:21,代码来源:ami.py

示例14: request_ssl_certificates

# 需要导入模块: import boto3 [as 别名]
# 或者: from boto3 import client [as 别名]
def request_ssl_certificates(region, dn):
    """
    Notes:
        * idempotent ops
        * store CertificateArn to dict_region_sslcerts
    """
    acm_client = boto3.client(service_name='acm', region_name=region)
    try:
        resp = acm_client.request_certificate(
            DomainName=dn,
            ValidationMethod='DNS',
            IdempotencyToken='112358',
        )
        dict_region_sslcerts[region].append(resp['CertificateArn'])
        print("[INFO] creating ssl certificate in region " + region + " for domain name " + dn)
        print(dn + ': ' + resp['CertificateArn'])
    except Exception as e:
        print("[ERROR] Unexpected error to request certificates: %s" % e) 
开发者ID:harmony-one,项目名称:harmony-ops,代码行数:20,代码来源:creation_certificates.py

示例15: get_existing_certs

# 需要导入模块: import boto3 [as 别名]
# 或者: from boto3 import client [as 别名]
def get_existing_certs(region, dn):

    acm_client = boto3.client(service_name='acm', region_name=region)
    dict_exist_sslcerts.clear()
    try:
        resp = acm_client.list_certificates(
            CertificateStatuses=['ISSUED', 'PENDING_VALIDATION'],
            MaxItems=1000,
        )
        for cert in resp['CertificateSummaryList']:
            if dn == cert['DomainName']:
                dict_exist_sslcerts[cert['DomainName']].append(cert['CertificateArn'])

        # pp.pprint(dict_exist_sslcerts)
        return dict_exist_sslcerts
    except Exception as e:
        print("[ERROR] Unexpected error to get exist certificates: %s" % e) 
开发者ID:harmony-one,项目名称:harmony-ops,代码行数:19,代码来源:creation_certificates.py


注:本文中的boto3.client方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。