如何使用AWS CLI仅按年龄多少来获取所有访问密钥

时间:2020-11-05 18:34:29

标签: amazon-web-services amazon-iam aws-cli

我想创建一个脚本,也许每24小时在一个cron作业中运行一个脚本,它将列出所有60天以上的访问密钥。

我还想将超过60天的密钥推入数组,以便可以对其进行迭代并执行其他选择。

我正在查看Managing access keys for IAM users - AWS Identity and Access Management,它有一个aws iam get-access-key-last-used命令,但这不是我想要的。但这是我能找到的壁橱东西。

我想获取当前日期的密钥-creation date > 60 days

我在想我的脚本看起来像这样:

# some of this is pseudocode just to 
# communicate what I'm envisioning.
# I don't actually know what to put
# here yet; need assistance.

myCommand = "aws cli get key where age > 60"
staleKeys=( $( $myCommand) )

for key in "${staleKeys[@]}"
do
   # log "${key}"
   # run another aws cli command with ${key} as a value
done

从AWS CLI可以做到这一点吗?

2 个答案:

答案 0 :(得分:2)

我使用以下 Python boto3 脚本,而不是 AWS CLI。

希望这对那些想要使用 boto3 的人有所帮助:

import boto3
from datetime import datetime, timezone

def utc_to_local(utc_dt):
    return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None)

def diff_dates(date1, date2):
    return abs(date2 - date1).days

resource = boto3.resource('iam')
client = boto3.client("iam")

KEY = 'LastUsedDate'

for user in resource.users.all():
    Metadata = client.list_access_keys(UserName=user.user_name)
    if Metadata['AccessKeyMetadata']:
        for key in user.access_keys.all():
            
            AccessId = key.access_key_id
            Status = key.status
            CreatedDate = key.create_date

            numOfDays = diff_dates(utc_to_local(datetime.utcnow()), utc_to_local(CreatedDate))
            LastUsed = client.get_access_key_last_used(AccessKeyId=AccessId)

            if (Status == "Active"):
                if KEY in LastUsed['AccessKeyLastUsed']:
                    print("User:", user.user_name,  "Key:", AccessId, "Last Used:", LastUsed['AccessKeyLastUsed'][KEY], "Age of Key:", numOfDays, "Days")
                else:
                    print("User:", user.user_name , "Key:",  AccessId, "Key is Active but NEVER USED")
            else:
                print("User:", user.user_name , "Key:",  AccessId, "Keys is InActive")
    else:
        print("User:", user.user_name , "No KEYS for this USER")

答案 1 :(得分:0)

我推荐Getting credential reports for your AWS account - AWS Identity and Access Management。这是一个自动过程,可以生成一个CSV文件,列出许多有关凭据的信息,包括:

  • 创建或最后一次更改用户访问密钥的日期和时间
  • 最近使用用户访问密钥签署AWS API请求的日期和时间

可以通过调用generate-credential-report,稍等片刻,然后调用get-credential-report来获得报告。响应需要进行base64解码。结果看起来像这样:

user,arn,user_creation_time,password_enabled,password_last_used,password_last_changed,password_next_rotation,mfa_active,access_key_1_active,access_key_1_last_rotated,access_key_1_last_used_date,access_key_1_last_used_region,access_key_1_last_used_service,access_key_2_active,access_key_2_last_rotated,access_key_2_last_used_date,access_key_2_last_used_region,access_key_2_last_used_service,cert_1_active,cert_1_last_rotated,cert_2_active,cert_2_last_rotated
user1,arn:aws:iam::111111111111:user/user1,2019-04-08T05:57:22+00:00,true,2020-05-20T10:55:03+00:00,2019-04-18T00:43:43+00:00,N/A,false,true,2019-04-08T05:57:24+00:00,2019-12-05T21:23:00+00:00,us-west-2,iot,true,2019-11-18T09:38:54+00:00,N/A,N/A,N/A,false,N/A,false,N/A

如果您决定自己生成信息,请注意list_access_keys()仅返回有关单个用户的信息。因此,您需要遍历所有用户,并为每个用户调用list_access_keys()以获取密钥的CreationDate

有关用法示例,请参见:How to scan your AWS account for old access keys using python - DEV Community