You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AWS CloudShell中获取当前用户的公网IP地址?

在AWS CloudShell中获取本地公网IP(用于自动化安全组配置)

核心思路:启动CloudShell会话时,AWS会在CloudTrail中记录发起请求的源IP(即你本地设备的公网IP),我们可以通过查询CloudTrail事件提取这个IP,无需额外打开外部网页。

步骤1:获取本地公网IP

执行以下命令(CloudShell默认已预装jq,无需额外安装):

# 获取当前登录用户的用户名
USER_NAME=$(aws sts get-caller-identity --query 'UserName' --output text)

# 查询CloudTrail中最新的CloudShell启动事件,提取用户源IP
USER_IP=$(aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=EventName,AttributeValue=StartEnvironment AttributeKey=Username,AttributeValue=$USER_NAME \
  --max-items 1 \
  --query 'Events[0].CloudTrailEvent' \
  | jq -r '.sourceIPAddress')

# 输出验证结果
echo "你的本地公网IP: $USER_IP"

步骤2:自动化添加IP到安全组

拿到IP后,直接用AWS CLI将其添加到目标安全组的入站规则中,示例如下(替换为你的安全组ID和需要开放的端口/协议):

# 配置目标安全组和规则参数
SECURITY_GROUP_ID="sg-xxxxxxxxx"
ALLOWED_PORT=22
ALLOWED_PROTOCOL=tcp

# 添加安全组入站规则
aws ec2 authorize-security-group-ingress \
  --group-id $SECURITY_GROUP_ID \
  --protocol $ALLOWED_PROTOCOL \
  --port $ALLOWED_PORT \
  --cidr "${USER_IP}/32"

注意事项

  • 确保CloudShell绑定的IAM角色拥有cloudtrail:LookupEvents和ec2:AuthorizeSecurityGroupIngress权限;
  • 如果会话启动时间较长,可添加--start-time和--end-time参数缩小CloudTrail事件查询范围,确保获取到正确的源IP。

内容的提问来源于stack exchange,提问作者m01010011

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 22:36:34