繁体   English   中英

AWS Boto3:请求中包含的安全令牌无效

[英]AWS Boto3: The security token included in the request is invalid

阅读此问题后如何使用boto3在EC2中SSH和运行命令? 我尝试使用SSM在EC2实例上自动运行命令。 但是,当我写这样的代码

def excute_command_on_instance(client, command, instance_id):
    response = client.send_command(
        DocumentName="AWS-RunShellScript", # One of AWS' preconfigured documents
        Parameters={'commands': command},
        InstanceIds=instance_id,
    )
    return response

# Using SSM in boto3 to send command to EC2 instances.
ssm_client = boto3.client('ssm')
commands = ['echo "hello world']
instance_id = running_instance[0:1]
excute_command_on_instance(ssm_client, commands, instance_id)

它让我想起了

botocore.exceptions.ClientError: An error occurred (AccessDeniedException) when calling the SendCommand operation: User: arn:aws:iam::62771xxxx946:user/Python_CloudComputing is not authorized to perform: ssm:SendCommand on resource: arn:aws:ec2:eu-west-2:6277xxxx3946:instance/i-074f862c3xxxxfc07

在我使用SSTclient生成凭据后,我得到了如下代码。

    def excute_command_on_instance(client, command, instance_id):
        response = client.send_command(
            DocumentName="AWS-RunShellScript", # One of AWS' preconfigured documents
            Parameters={'commands': command},
            InstanceIds=instance_id,
        )
        return response

    # Using SSM in boto3 to send command to EC2 instances.
    sts = boto3.client('sts')
    sts_response = sts.get_session_token()
    ACCESS_KEY = sts_response['Credentials']['AccessKeyId']
    SECRET_KEY = sts_response['Credentials']['SecretAccessKey']
    ssm_client = boto3.client(
        'ssm',
        aws_access_key_id=ACCESS_KEY,
        aws_secret_access_key=SECRET_KEY,
    )
    commands = ['echo "hello world']
    instance_id = running_instance[0:1]
    excute_command_on_instance(ssm_client, commands, instance_id)

但是,这次它让我想起了

botocore.exceptions.ClientError: An error occurred (UnrecognizedClientException) when calling the SendCommand operation: The security token included in the request is invalid.

谁能告诉我如何解决这个问题?

您缺少IAM用户或访问SSM的角色的权限。

您还尝试使用STS来获取访问权限,这使您需要执行的操作过于复杂。 STS需要承担的策略需要相同的权限。 使用STS(最小特权规则)有很多好的案例,但我认为你不需要STS。

亚马逊为SSM提供了预定义的策略,您可以快速添加到策略或角色,例如:

AmazonEC2RoleForSSM
AmazonSSMFullAccess
AmazonSSMReadOnlyAccess

此链接将帮助您配置对Systems Manager的访问:

配置对Systems Manager的访问

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM