VS Code通过SSM代理SSH连接AWS Cloud9 EC2实例失败求助
无法通过ssm-proxy.sh脚本用VS Code远程连接AWS Cloud9
问题背景
按照AWS官方教程尝试用Cloud9作为VS Code后端环境,直接SSH连接正常,但通过ssm-proxy.sh代理脚本连接时失败。
已确认的配置情况
可正常工作的SSH配置
Host test1 HostName xx.xxx.xxx.xx User ec2-user IdentityFile ~/.ssh/vscloud9
无法工作的SSH配置
Host cloud9 IdentityFile ~/.ssh/vscloud9 User ec2-user HostName i-xxxxxxxxxxxxx ProxyCommand sh -c "~/.ssh/ssm-proxy.sh %h %p"
其他配置细节
- AWS CLI已配置默认命名配置文件(使用根用户访问密钥,权限无限制)
- ssm-proxy.sh内的配置参数:
AWS_PROFILE='default' AWS_REGION='eu-west-2' MAX_ITERATION=5 SLEEP_DURATION=5 - 目标实例安全组已开放0.0.0.0/0的SSH访问
- 使用相同密钥对的普通SSH连接正常,排除密钥问题
- 使用VS Code Remote - SSH扩展
SSH Debug输出(已翻译)
OpenSSH_9.0p1, LibreSSL 3.3.6 debug1: 读取配置数据 /Users/myname/.ssh/config debug1: /Users/myname/.ssh/config 第6行: 应用cloud9的配置选项 debug1: 读取配置数据 /etc/ssh/ssh_config debug1: /etc/ssh/ssh_config 第21行: include /etc/ssh/ssh_config.d/* 未匹配到任何文件 debug1: /etc/ssh/ssh_config 第54行: 应用全局配置选项 debug1: 认证提供者$SSH_SK_PROVIDER未解析;已禁用 debug1: 执行代理命令: exec sh -c "~/.ssh/ssm-proxy.sh i-xxxxxxxxxxxxxx 22" debug1: 身份文件 /Users/myname/.ssh/vscloud9 类型为0 debug1: 身份文件 /Users/myname/.ssh/vscloud9-cert 类型为-1 debug1: 本地版本字符串 SSH-2.0-OpenSSH_9.0 debug1: 密钥交换识别: banner行0: { debug1: 密钥交换识别: banner行1: "StartingInstances": [ debug1: 密钥交换识别: banner行2: { debug1: 密钥交换识别: banner行3: "CurrentState": { debug1: 密钥交换识别: banner行4: "Code": 0, debug1: 密钥交换识别: banner行5: "Name": "pending" debug1: 密钥交换识别: banner行6: }, debug1: 密钥交换识别: banner行7: "InstanceId": "i-xxxxxxxxxxxxxx", debug1: 密钥交换识别: banner行8: "PreviousState": { debug1: 密钥交换识别: banner行9: "Code": 80, debug1: 密钥交换识别: banner行10: "Name": "stopped" debug1: 密钥交换识别: banner行11: } debug1: 密钥交换识别: banner行12: } debug1: 密钥交换识别: banner行13: ] debug1: 密钥交换识别: banner行14: } kex_exchange_identification: 连接被远程主机关闭 Connection closed by UNKNOWN port 65535
故障分析与解决步骤
从debug日志可以明确,脚本触发了实例启动操作(实例状态从stopped变为pending),但后续连接失败,原因及解决方法如下:
脚本未等待实例完全就绪
日志显示实例处于pending状态时,脚本就尝试建立SSM隧道,但实例还未进入running状态,且SSM代理尚未在线。- 修改脚本参数:将
MAX_ITERATION改为10、SLEEP_DURATION改为10,给实例足够的启动时间; - 优化脚本逻辑:增加判断,只有当实例状态为
running且ssm describe-instance-information返回实例在线时,才建立隧道。
- 修改脚本参数:将
脚本输出干扰SSH连接
脚本启动实例时输出的JSON格式状态信息被SSH当作连接的banner内容,导致密钥交换流程中断。- 修改脚本:将
aws ec2 start-instances命令的输出重定向到/dev/null,例如:aws ec2 start-instances --instance-ids $INSTANCE_ID > /dev/null 2>&1
- 修改脚本:将
SSM代理未运行
确认目标Cloud9实例上的amazon-ssm-agent服务是否正常运行:- 先手动启动实例,通过SSH登录后执行
sudo systemctl status amazon-ssm-agent,如果未运行则启动服务:sudo systemctl start amazon-ssm-agent并设置开机自启。
- 先手动启动实例,通过SSH登录后执行
AWS区域配置不匹配
确认AWS CLI默认区域与脚本中的eu-west-2一致:- 执行
aws configure get region查看默认区域,若不一致则修改CLI配置或脚本中的AWS_REGION参数。
- 执行
内容的提问来源于stack exchange,提问作者Anthony
相关产品推荐
相关产品推荐

