

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 设置远程 IDE
<a name="remote-access-local-ide-setup"></a>

管理员完成中的说明后[通过远程访问将您的远程 IDE 连接到 SageMaker 空间](remote-access.md)，您可以将远程 IDE 连接到远程 SageMaker 空间。

**Topics**
+ [设置本地环境](#remote-access-local-ide-setup-local-environment)
+ [连接到您的远程 IDE](#remote-access-local-ide-setup-local-vs-code)
+ [连接到具有无互联网访问权限的子网的 VPC](remote-access-local-ide-setup-vpc-no-internet.md)
+ [筛选您的 Studio 空间](remote-access-local-ide-setup-filter.md)

## 设置本地环境
<a name="remote-access-local-ide-setup-local-environment"></a>

在本地计算机上安装首选的远程 IDE：
+ [Visual Studio Code](https://code.visualstudio.com/)
+ [Kiro](https://kiro.dev/)
+ [Cursor](https://cursor.com/home)

有关版本要求的信息，请参阅[IDE 版本要求](remote-access.md#remote-access-ide-version-requirements)。

## 连接到您的远程 IDE
<a name="remote-access-local-ide-setup-local-vs-code"></a>

在建立从远程 IDE 到远程 SageMaker 空间的连接之前，必须由管理员进行连接[设置远程访问](remote-access-remote-setup.md)。您的管理员为您设置了一种特定的建立连接的方法。选择已为您设置的方法。

**Topics**
+ [方法 1：来自 Studio UI 的深度链接](#remote-access-local-ide-setup-local-vs-code-method-1-deep-link-from-studio-ui)
+ [方法 2：远程 IDE 中的 AWS 工具包](#remote-access-local-ide-setup-local-vs-code-method-2-aws-toolkit-in-vs-code)
+ [方法 3：通过 SSH CLI 从终端连接](#remote-access-local-ide-setup-local-vs-code-method-3-connect-from-the-terminal-via-ssh-cli)

### 方法 1：来自 Studio UI 的深度链接
<a name="remote-access-local-ide-setup-local-vs-code-method-1-deep-link-from-studio-ui"></a>

执行以下过程，使用深度链接建立连接。

1. [启动 Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html#studio-updated-launch-console)。

1. 在 Studio UI 中，导航到您的空间。

1. 在首选 IDE **中选择 “在 VS Code** **中打开”、“在 Kiro** **中打开” 或 “在光标中打开**” 按钮。确保您的首选 IDE 已安装在本地计算机上。

1. 出现提示时，确认打开 IDE。您的 IDE 将打开并显示另一个弹出窗口进行确认。完成后，远程连接即建立。

### 方法 2：远程 IDE 中的 AWS 工具包
<a name="remote-access-local-ide-setup-local-vs-code-method-2-aws-toolkit-in-vs-code"></a>

执行以下过程，使用 AWS Toolkit for Visual Studio Code建立连接。此方法可用于 VS Code、Kiro 和 Cursor。

1. 打开你的远程 IDE（VS Code、Kiro 或 Cursor）。

1. 打开 AWS 工具包扩展。

1. [连接到 AWS](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/connect.html)。

1. 在 AWS 资源管理器中，展开 **SageMaker AI**，然后展开 **Studio**。

1. 找到您的 Studio 空间。

1. 选择该空间旁边的**连接**图标即可将其启动。
**注意**  
停止并重新启动 Toolkit for Visual Studio 中的空间以启用远程访问（如果尚未连接）。
如果空间未使用支持的[实例大小](https://docs.aws.amazon.com/sagemaker/latest/dg/remote-access.html#remote-access-instance-requirements)，系统将要求您更改实例。

### 方法 3：通过 SSH CLI 从终端连接
<a name="remote-access-local-ide-setup-local-vs-code-method-3-connect-from-the-terminal-via-ssh-cli"></a>

选择以下平台选项之一，查看使用 SSH CLI 建立连接的过程。

**注意**  
在按照以下说明进行操作之前，请确保[本地计算机先决条件](remote-access.md#remote-access-local-prerequisites)已安装最新版本。
如果是[自带映像（BYOI）](studio-updated-byoi.md)，请确保已安装中列出的必需依赖项，[映像要求](remote-access.md#remote-access-image-requirements)然后再继续

------
#### [ Linux/macOS ]

创建一个 Shell 脚本（例如 `/home/user/sagemaker_connect.sh`）：

```
#!/bin/bash
# Disable the -x option if printing each command is not needed.
set -exuo pipefail

SPACE_ARN="$1"
AWS_PROFILE="${2:-}"

# Validate ARN and extract region
if [[ "$SPACE_ARN" =~ ^arn:aws[-a-z]*:sagemaker:([a-z0-9-]+):[0-9]{12}:space\/[^\/]+\/[^\/]+$ ]]; then
    AWS_REGION="${BASH_REMATCH[1]}"
else
    echo "Error: Invalid SageMaker Studio Space ARN format."
    exit 1
fi

# Optional profile flag
PROFILE_ARG=()
if [[ -n "$AWS_PROFILE" ]]; then
    PROFILE_ARG=(--profile "$AWS_PROFILE")
fi

# Start session
START_SESSION_JSON=$(aws sagemaker start-session \
    --resource-identifier "$SPACE_ARN" \
    --region "${AWS_REGION}" \
    "${PROFILE_ARG[@]}")

# Extract fields using grep and sed
SESSION_ID=$(echo "$START_SESSION_JSON" | grep -o '"SessionId": "[^"]*"' | sed 's/.*: "//;s/"$//')
STREAM_URL=$(echo "$START_SESSION_JSON" | grep -o '"StreamUrl": "[^"]*"' | sed 's/.*: "//;s/"$//')
TOKEN=$(echo "$START_SESSION_JSON" | grep -o '"TokenValue": "[^"]*"' | sed 's/.*: "//;s/"$//')

# Validate extracted values
if [[ -z "$SESSION_ID" || -z "$STREAM_URL" || -z "$TOKEN" ]]; then
    echo "Error: Failed to extract session information from sagemaker start session response."
    exit 1
fi

# Call session-manager-plugin
session-manager-plugin \
    "{\"streamUrl\":\"$STREAM_URL\",\"tokenValue\":\"$TOKEN\",\"sessionId\":\"$SESSION_ID\"}" \
    "$AWS_REGION" "StartSession"
```

1. 使该脚本成为可执行文件：

   ```
   chmod +x /home/user/sagemaker_connect.sh
   ```

1. 配置 `$HOME/.ssh/config` 以添加以下条目：

```
Host space-name
  HostName 'arn:PARTITION:sagemaker:us-east-1:111122223333:space/domain-id/space-name'
  ProxyCommand '/home/user/sagemaker_connect.sh' '%h'
  ForwardAgent yes
  AddKeysToAgent yes
  StrictHostKeyChecking accept-new
```

例如，`PARTITION` 可以是 `aws`。

如果您需要使用已[命名的 AWS 凭据配置文件](https://docs.aws.amazon.com/cli/v1/userguide/cli-configure-files.html#cli-configure-files-using-profiles)，请按如下方式更改代理命令：

```
  ProxyCommand '/home/user/sagemaker_connect.sh' '%h' YOUR_CREDENTIAL_PROFILE_NAME
```
+ 通过 SSH 进行连接或运行 SCP 命令：

```
ssh space-name
scp file_abc space-name:/tmp/
```

------
#### [ Windows ]

**Windows 的先决条件：**
+ PowerShell 5.1 或更高版本
+ SSH 客户端（推荐 OpenSSH）

创建 PowerShell 脚本（例如，`C:\Users\user-name\sagemaker_connect.ps1`）：

```
# sagemaker_connect.ps1
param(
    [Parameter(Mandatory=$true)]
    [string]$SpaceArn,

    [Parameter(Mandatory=$false)]
    [string]$AwsProfile = ""
)

# Enable error handling
$ErrorActionPreference = "Stop"

# Validate ARN and extract region
if ($SpaceArn -match "^arn:aws[-a-z]*:sagemaker:([a-z0-9-]+):[0-9]{12}:space\/[^\/]+\/[^\/]+$") {
    $AwsRegion = $Matches[1]
} else {
    Write-Error "Error: Invalid SageMaker Studio Space ARN format."
    exit 1
}

# Build AWS CLI command
$awsCommand = @("sagemaker", "start-session", "--resource-identifier", $SpaceArn, "--region", $AwsRegion)

if ($AwsProfile) {
    $awsCommand += @("--profile", $AwsProfile)
}

try {
    # Start session and capture output
    Write-Host "Starting SageMaker session..." -ForegroundColor Green
    $startSessionOutput = & aws @awsCommand

    # Try to parse JSON response
    try {
        $sessionData = $startSessionOutput | ConvertFrom-Json
    } catch {
        Write-Error "Failed to parse JSON response: $_"
        Write-Host "Raw response was:" -ForegroundColor Yellow
        Write-Host $startSessionOutput
        exit 1
    }

    $sessionId = $sessionData.SessionId
    $streamUrl = $sessionData.StreamUrl
    $token = $sessionData.TokenValue

    # Validate extracted values
    if (-not $sessionId -or -not $streamUrl -or -not $token) {
        Write-Error "Error: Failed to extract session information from sagemaker start session response."
        Write-Host "Parsed response was:" -ForegroundColor Yellow
        Write-Host ($sessionData | ConvertTo-Json)
        exit 1
    }

    Write-Host "Session started successfully. Connecting..." -ForegroundColor Green

    # Create session manager plugin command
    $sessionJson = @{
        streamUrl = $streamUrl
        tokenValue = $token
        sessionId = $sessionId
    } | ConvertTo-Json -Compress

    # Escape the JSON string
    $escapedJson = $sessionJson -replace '"', '\"'

    # Call session-manager-plugin
    & session-manager-plugin "$escapedJson" $AwsRegion "StartSession"

} catch {
    Write-Error "Failed to start session: $_"
    exit 1
}
```
+ 配置 `C:\Users\user-name\.ssh\config` 以添加以下条目：

```
Host space-name                            
  HostName "arn:aws:sagemaker:us-east-1:111122223333:space/domain-id/space-name"
  ProxyCommand "C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe" -ExecutionPolicy RemoteSigned -File "C:\\Users\\user-name\\sagemaker_connect.ps1" "%h"
  ForwardAgent yes
  AddKeysToAgent yes
  User sagemaker-user
  StrictHostKeyChecking accept-new
```

------