你可以通过电子邮件获取AWS IAM报告。

huangapple go评论64阅读模式
英文:

How can I take AWS iam report through email

问题

以下是您要的代码的翻译部分:

"我想使用 AWS Lambda 创建一个 AWS IAM 报告作为 Excel 文件并通过电子邮件发送给我。所以我编写了这段代码,并且它有效。但当我打开这个 Excel 文件时,我注意到其中的一些内容为空。

last_login, password_age

我想知道为什么它们为空。

这是我的代码。谢谢"

如果您需要进一步的帮助,请随时提问。

英文:

I want to use AWS lambda to create an AWS IAM report as an excel file and send it email to me.
So I made this code and it worked. but When I opened this excel file, I noticed that several topics were blank.

last_login, password_age

I want to know why it is blank.

this is my code. Thanks

import boto3
import pandas as pd
import os
from io import BytesIO
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart

def lambda_handler(event, context):
    client = boto3.client('iam')
    response = client.list_users()
    users_info = []
    for user in response['Users']:
        username = user['UserName']
        groups = client.list_groups_for_user(UserName=username)['Groups']
        last_login = client.get_login_profile(UserName=username).get('PasswordLastUsed')
        mfa_enabled = client.list_mfa_devices(UserName=username).get('MFADevices') != []
        password_age = (pd.Timestamp.now(tz='utc') - pd.Timestamp(last_login)).days if last_login else None
        access_keys = client.list_access_keys(UserName=username).get('AccessKeyMetadata')
        active_key_age = None
        for access_key in access_keys:
            if access_key['Status'] == 'Active':
                active_key_age = (pd.Timestamp.now(tz='utc') - pd.Timestamp(access_key['CreateDate'])).days
                break
        user_info = {
            'Username': username,
            'Groups': ', '.join([group['GroupName'] for group in groups]),
            'Last Login': str(last_login) if last_login else '',
            'MFA Enabled': mfa_enabled,
            'Password Age (Days)': password_age,
            'Active Key Age (Days)': active_key_age
        }
        users_info.append(user_info)
    df = pd.DataFrame(users_info)
    output = BytesIO()
    writer = pd.ExcelWriter(output, engine='xlsxwriter')
    df.to_excel(writer, sheet_name='IAM Users Info', index=False, startrow=1)
    workbook = writer.book
    worksheet = writer.sheets['IAM Users Info']
    header_format = workbook.add_format({
        'bold': True,
        'text_wrap': True,
        'valign': 'top',
        'fg_color': '#D7E4BC',
        'border': 1
    })
    for col_num, value in enumerate(df.columns.values):
        worksheet.write(0, col_num, value, header_format)
        column_len = df[value].astype(str).str.len().max()
        column_len = max(column_len, len(value)) + 3
        worksheet.set_column(col_num, col_num, column_len)
    writer.save()
    from_address = 'my-mail'
    to_address = 'my-mail'
    subject = 'IAM Users Info'
    body = 'Please see the attached file for IAM Users Info.'  
    client = boto3.client('ses')   
    attachment = MIMEApplication(output.getvalue(), _subtype='vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    attachment.add_header('Content-Disposition', 'attachment', filename='iam_users_info.xlsx')
    message = MIMEMultipart

答案1

得分: 1

以下是您的代码的翻译部分:

你正在使用 `client.get_login_profile` 获取 `last_login`,但它返回有关用户登录配置文件而非登录活动的信息请改用 `client.get_user()`,同时 `password_age` 计算当前时间戳和 `last_login` 之间的差异但由于 `last_login` 并未按我们所需的方式检索因此 `password_age` 也不正确

我已经更新了您的代码如下

import boto3
import pandas as pd
import os
from io import BytesIO
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart

def lambda_handler(event, context):
    client = boto3.client('iam')
    response = client.list_users()
    users_info = []
    for user in response['Users']:
        username = user['UserName']
        groups = client.list_groups_for_user(UserName=username)['Groups']
        user_data = client.get_user(UserName=username)
        last_login = user_data['User'].get('PasswordLastUsed')
        mfa_enabled = client.list_mfa_devices(UserName=username).get('MFADevices') != []
        password_age = (pd.Timestamp.now(tz='utc') - pd.Timestamp(last_login)).days if last_login else None
        access_keys = client.list_access_keys(UserName=username).get('AccessKeyMetadata')
        active_key_age = None
        for access_key in access_keys:
            if access_key['Status'] == 'Active':
                active_key_age = (pd.Timestamp.now(tz='utc') - pd.Timestamp(access_key['CreateDate'])).days
                break
        user_info = {
            'Username': username,
            'Groups': ', '.join([group['GroupName'] for group in groups]),
            'Last Login': str(last_login) if last_login else '',
            'MFA Enabled': mfa_enabled,
            'Password Age (Days)': password_age,
            'Active Key Age (Days)': active_key_age
        }
        users_info.append(user_info)
    df = pd.DataFrame(users_info)
    output = BytesIO()
    writer = pd.ExcelWriter(output, engine='xlsxwriter')
    df.to_excel(writer, sheet_name='IAM Users Info', index=False, startrow=1)
    workbook = writer.book
    worksheet = writer.sheets['IAM Users Info']
    header_format = workbook.add_format({
        'bold': True,
        'text_wrap': True,
        'valign': 'top',
        'fg_color': '#D7E4BC',
        'border': 1
    })
    for col_num, value in enumerate(df.columns.values):
        worksheet.write(0, col_num, value, header_format)
        column_len = df[value].astype(str).str.len().max()
        column_len = max(column_len, len(value)) + 3
        worksheet.set_column(col_num, col_num, column_len)
    writer.save()
    from_address = 'my-mail'
    to_address = 'my-mail'
    subject = 'IAM Users Info'
    body = '请查看附加的 IAM 用户信息文件。'
    client = boto3.client('ses')
    attachment = MIMEApplication(output.getvalue(), _subtype='vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    attachment.add_header('Content-Disposition', 'attachment', filename='iam_users_info.xlsx')
    message = MIMEMultipart

希望这有助于您理解代码的翻译。如果您有任何问题,请随时提问。

英文:

You are using client.get_login_profile For last_login but it return informations about the login profile of the user not the login activity, use client.get_user() instead, also password_age calculate the difference between the current timestamp and last_login but last_login is not retrieved as we want so password_age is incorrect as well.

I updated your code like that:

import boto3
import pandas as pd
import os
from io import BytesIO
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
def lambda_handler(event, context):
client = boto3.client('iam')
response = client.list_users()
users_info = []
for user in response['Users']:
username = user['UserName']
groups = client.list_groups_for_user(UserName=username)['Groups']
user_data = client.get_user(UserName=username)
last_login = user_data['User'].get('PasswordLastUsed')
mfa_enabled = client.list_mfa_devices(UserName=username).get('MFADevices') != []
password_age = (pd.Timestamp.now(tz='utc') - pd.Timestamp(last_login)).days if last_login else None
access_keys = client.list_access_keys(UserName=username).get('AccessKeyMetadata')
active_key_age = None
for access_key in access_keys:
if access_key['Status'] == 'Active':
active_key_age = (pd.Timestamp.now(tz='utc') - pd.Timestamp(access_key['CreateDate'])).days
break
user_info = {
'Username': username,
'Groups': ', '.join([group['GroupName'] for group in groups]),
'Last Login': str(last_login) if last_login else '',
'MFA Enabled': mfa_enabled,
'Password Age (Days)': password_age,
'Active Key Age (Days)': active_key_age
}
users_info.append(user_info)
df = pd.DataFrame(users_info)
output = BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
df.to_excel(writer, sheet_name='IAM Users Info', index=False, startrow=1)
workbook = writer.book
worksheet = writer.sheets['IAM Users Info']
header_format = workbook.add_format({
'bold': True,
'text_wrap': True,
'valign': 'top',
'fg_color': '#D7E4BC',
'border': 1
})
for col_num, value in enumerate(df.columns.values):
worksheet.write(0, col_num, value, header_format)
column_len = df[value].astype(str).str.len().max()
column_len = max(column_len, len(value)) + 3
worksheet.set_column(col_num, col_num, column_len)
writer.save()
from_address = 'my-mail'
to_address = 'my-mail'
subject = 'IAM Users Info'
body = 'Please see the attached file for IAM Users Info.'  
client = boto3.client('ses')   
attachment = MIMEApplication(output.getvalue(), _subtype='vnd.openxmlformats-officedocument.spreadsheetml.sheet')
attachment.add_header('Content-Disposition', 'attachment', filename='iam_users_info.xlsx')
message = MIMEMultipart

huangapple
  • 本文由 发表于 2023年4月10日 21:31:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75977576.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定