如何通过编程方式获取AWS SSO会话的过期时间?
解决方案
方法一:Shell脚本(依赖AWS CLI和jq)
SSO登录后,AWS会在~/.aws/sso/cache/目录下生成缓存JSON文件,其中包含会话的过期时间expiresAt字段。我们可以解析这个文件获取过期时间,无需频繁调用STS接口。
示例脚本
#!/bin/bash # 替换为你的SSO起始URL(可通过aws configure get sso_start_url获取) SSO_START_URL="https://your-sso-domain.awsapps.com/start" # 提前告警阈值(1小时=3600秒) ALERT_THRESHOLD=3600 # 匹配对应SSO配置的缓存文件 CACHE_FILE=$(ls ~/.aws/sso/cache/*.json | xargs grep -l "$SSO_START_URL") if [ -z "$CACHE_FILE" ]; then echo "未找到对应SSO会话的缓存文件" exit 1 fi # 解析过期时间并转换为时间戳 EXPIRE_TIMESTAMP=$(jq -r '.expiresAt' "$CACHE_FILE" | date -j -f "%Y-%m-%dT%H:%M:%SZ" +%s) CURRENT_TIMESTAMP=$(date +%s) TIME_REMAINING=$((EXPIRE_TIMESTAMP - CURRENT_TIMESTAMP)) if [ "$TIME_REMAINING" -lt "$ALERT_THRESHOLD" ]; then echo "警告:AWS SSO会话将在$((TIME_REMAINING/60))分钟后过期,请及时重新登录" else echo "AWS SSO会话剩余时间:$((TIME_REMAINING/3600))小时$(((TIME_REMAINING%3600)/60))分钟" fi
说明
- 需提前安装
jq工具(JSON解析用),可通过brew install jq或apt-get install jq完成安装 - 脚本自动匹配对应SSO起始URL的缓存文件,计算剩余会话时长,当剩余时间不足1小时时触发告警
方法二:Python Boto3实现
使用Boto3加载SSO配置的profile后,可直接从会话凭证中获取过期时间,无需额外轮询STS接口。
示例代码
import boto3 from datetime import datetime, timedelta def check_sso_session_expiry(profile_name="your-sso-profile", alert_hours=1): # 加载指定的SSO profile session = boto3.Session(profile_name=profile_name) credentials = session.get_credentials() if not credentials or not hasattr(credentials, 'expiration'): print("无法获取会话过期时间,请确认SSO登录状态") return expire_time = credentials.expiration current_time = datetime.utcnow() time_remaining = expire_time - current_time if time_remaining < timedelta(hours=alert_hours): print(f"警告:AWS SSO会话将在{time_remaining.total_seconds()//60}分钟后过期,请重新登录") else: print(f"AWS SSO会话剩余时间:{time_remaining.days}天{time_remaining.seconds//3600}小时{(time_remaining.seconds%3600)//60}分钟") if __name__ == "__main__": # 替换为你的SSO配置profile名称 check_sso_session_expiry(profile_name="my-sso-profile", alert_hours=1)
说明
- 确保已通过
aws configure sso完成SSO profile的配置 - Boto3会自动从SSO缓存中加载凭证及过期时间,无需手动解析文件
- 当剩余时间小于指定告警小时数(默认1小时)时,输出提醒信息
内容的提问来源于stack exchange,提问作者Darren Oakey
相关产品推荐
相关产品推荐

