---
title: encoded-command-pattern
created: 2026-06-27
updated: 2026-06-27
type: concept
tags: [ssh, hermes-agent, pitfall, best-practice]
sources: [raw/articles/seomu-202606-history.md]
confidence: high
---

# SSH PowerShell EncodedCommand 패턴

## 왜 필요한가?

SSH로 PowerShell 명령을 직접 보내면 다음 문제 발생:
- `\` 이스케이프 다중 중첩 (bash → SSH → PowerShell)
- `$` 변수 bash가 잘못 해석 (`\$` → PowerShell literal `\$`)
- 따옴표 충돌 (작은따옴표, 큰따옴표, JSON escape)
- 한글 깨짐

## 해결: EncodedCommand (UTF-16LE base64)

```python
import subprocess, base64

ps = '$p = \'C:\\Users\\lee\\file.png\'; if (Test-Path $p) { Write-Host "OK" }'
ps_b64 = base64.b64encode(ps.encode('utf-16le')).decode()

r = subprocess.run(['ssh', '-o', 'ConnectTimeout=10', 'seomu',
                    f'powershell -NoProfile -EncodedCommand {ps_b64}'],
                   capture_output=True, timeout=30)
```

## 장점

| 항목 | 효과 |
|---|---|
| **이스케이프 0** | bash/SH/PowerShell 모두 escape 불필요 |
| **`$` 변수 정상** | PowerShell `$var` 그대로 사용 |
| **따옴표 자유** | `'`, `"`, 백틱 모두 OK |
| **백슬래시 안전** | `\\` 그대로 |
| **한글 안전** | UTF-16LE → PowerShell 자동 디코드 |

## stdin 파이프 패턴 (대용량)

```python
# base64 결과를 stdin으로 전달
ps = '$b64=[Console]::In.ReadToEnd().Trim(); $bytes=[Convert]::FromBase64String($b64); ...'
ps_b64 = base64.b64encode(ps.encode('utf-16le')).decode()

r = subprocess.run(['ssh', 'seomu', f'powershell -EncodedCommand {ps_b64}'],
                   input=b64_bytes, capture_output=True, timeout=30)
```

**주의**: `[Console]::In.ReadToEnd()` 사용 (Linux 파일 경로 직접 참조 시 Windows 해석 오류).

## 검증된 실전 사례 (2026-06-26~27)

| 사례 | 용도 |
|---|---|
| 스크린샷 base64 인코딩 | 1920×1080 PNG → base64 (485KB) → Linux 다운로드 |
| 1KB 미만 코드 배포 | EncodedCommand 한 줄 |
| Win32 API 호출 | Add-Type + EnumWindows 등 |
| 파일 저장/디코드 | base64 → WriteAllBytes |
| CLIXML 파싱 | `<ToString>` 태그 추출 |

## 주의사항

| # | 함정 |
|---|---|
| 1 | `Format-List`/`Format-Table` 출력 → CLIXML → `<ToString>` 추출 필요 |
| 2 | base64에 `+`, `/`, `=` 문자 → SSH 명령줄에서 문제 가능 (보통 OK) |
| 3 | 50KB+ base64 → /exec body 직접 시 HTTP 500 → stdin 파이프 |
| 4 | 한글 Write-Host → 표시만 `***` 마스킹 (실제 값은 OK) |

## 우회 패턴 비교

| 패턴 | 안전도 | 토큰 마스킹 | 한글 | 속도 |
|---|---|---|---|---|
| **EncodedCommand** | ⭐⭐⭐ | 영향 적음 | ✅ | 보통 |
| stdin 파이프 | ⭐⭐⭐ | 영향 적음 | ✅ | 보통 |
| JSON escape | ⭐ | 영향 받음 | ⚠️ | 느림 |
| 작은따옴표 변수 | ⭐ | 영향 적음 | ✅ | 보통 |

## 관련 페이지

- [[seomu-pc]]
- [[hermes-agent]]
- [[token-masking]]
