タイトル: SSH
SEOタイトル: SSH 完全ガイド — 認証/鍵/config/トンネル/ポートフォワード
| この記事の要点 |
|
SSH とは
SSH (Secure Shell) は、暗号化された通信路を介してリモートホストにログインし、コマンド実行・ファイル転送・ポートフォワーディングを行うためのプロトコル / ツールです。RFC 4251〜4254 で定義されており、TCP のポート 22 を使用します。
主な実装は OpenSSH(オープンソース)。Linux / macOS には標準搭載され、Windows 10 (1809) 以降にも標準で含まれます。
基本コマンド
# ホストにログイン
ssh user@example.com
# ポート指定
ssh -p 2222 user@example.com
# リモートでコマンド実行(ログインしない)
ssh user@example.com 'uptime; df -h'
# X 転送(GUI アプリ転送)
ssh -X user@example.com xeyes
# verbose(接続トラブル調査)
ssh -v user@example.com # -vv, -vvv で更に詳細
# 強制終了して再接続したい
~. # チルダ→ドットで強制切断(ssh エスケープシーケンス)
公開鍵認証のセットアップ
パスワード認証はブルートフォース攻撃の的になります。サーバ運用では公開鍵認証に切り替えるのが鉄則です。
# 鍵ペア生成 (ed25519 推奨、なければ RSA 4096)
ssh-keygen -t ed25519 -C "you@example.com"
ssh-keygen -t rsa -b 4096 -C "you@example.com"
# 出力先
# ~/.ssh/id_ed25519 秘密鍵(権限 600 / 公開禁止)
# ~/.ssh/id_ed25519.pub 公開鍵(サーバに登録する)
# パスフレーズは推奨(紛失時の保険)
# Enter passphrase: ********
# サーバへ公開鍵を登録
ssh-copy-id user@example.com
# パスワードを 1 度入力 → ~/.ssh/authorized_keys に追記される
# 手動でやる場合
cat ~/.ssh/id_ed25519.pub | ssh user@example.com \
'mkdir -p ~/.ssh && chmod 700 ~/.ssh && \
cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys'
# 接続確認
ssh user@example.com
# パスワードを聞かれずに入れれば成功
~/.ssh/config で接続情報を集約
毎回 ssh -p 2222 -i ~/.ssh/special_key admin@prod.example.com と打つのは面倒。~/.ssh/config に書けば ssh prod の一発接続にできます。
# ~/.ssh/config (パーミッション 600)
Host prod
HostName prod.example.com
User admin
Port 2222
IdentityFile ~/.ssh/id_prod_ed25519
ServerAliveInterval 60
Host stage
HostName 10.20.30.40
User deploy
IdentityFile ~/.ssh/id_deploy
ProxyJump prod # prod 経由で接続(踏み台)
Host github.com
User git
IdentityFile ~/.ssh/id_ed25519_github
AddKeysToAgent yes
# ワイルドカード
Host *.internal
User ops
StrictHostKeyChecking no
# 全 Host のデフォルト
Host *
ServerAliveInterval 30
ServerAliveCountMax 3
Compression yes
主要オプション:
| キー | 意味 |
|---|---|
HostName | 実 IP / FQDN |
User | ログインユーザ |
Port | ポート番号 |
IdentityFile | 秘密鍵パス(複数指定可) |
ProxyJump | 踏み台ホスト(多段 SSH) |
ServerAliveInterval | keepalive 秒 |
ForwardAgent | SSH エージェント転送 |
StrictHostKeyChecking | known_hosts 検査 |
LocalForward | ローカル → リモート ポート転送 |
RemoteForward | リモート → ローカル ポート転送 |
SCP / SFTP でファイル転送
# ローカル → リモート
scp local.txt user@example.com:/remote/dir/
# リモート → ローカル
scp user@example.com:/remote/file.log .
# ディレクトリ再帰
scp -r ./dist/ user@example.com:/var/www/
# ポート指定
scp -P 2222 file user@example.com:/tmp/
# 対話 SFTP
sftp user@example.com
sftp> put localfile
sftp> get remotefile
sftp> ls
sftp> bye
# rsync(差分のみ。SCP より高速)
rsync -avz --progress ./dist/ user@example.com:/var/www/
ポートフォワーディング
ローカルフォワード (-L)
ローカルのポート → SSH 経由でリモート側からアクセス。「自分の PC の 3306 ポートを叩くと、リモートの DB に繋がる」用途。
# ローカル 3306 → 踏み台経由 → 社内 DB の 3306
ssh -L 3306:internal-db.local:3306 user@bastion.example.com
# ローカルから接続
mysql -h 127.0.0.1 -P 3306 -u root -p
# → 実際は internal-db.local の MySQL に接続
# バックグラウンドで張りっぱなし
ssh -fN -L 3306:internal-db.local:3306 user@bastion.example.com
リモートフォワード (-R)
リモートのポート → SSH 経由でローカル側からアクセス。「自宅 PC の Web サーバを、出先のサーバから見える状態にする」用途。
# サーバの 8080 → 自分の PC の 80 へ
ssh -R 8080:localhost:80 user@example.com
# 受信側で確認
curl http://localhost:8080
# 自宅 PC の Web サーバが叩かれる
動的フォワード / SOCKS プロキシ (-D)
# ローカル 1080 を SOCKS プロキシ化
ssh -D 1080 user@example.com
# Chrome / Firefox の SOCKS 設定: 127.0.0.1:1080
# → 全 HTTP リクエストがサーバ経由になる
# 海外サーバ経由ブラウジング、社内専用 Web 閲覧に
SSH Agent
パスフレーズ付き鍵を毎回打つのは面倒。ssh-agent に鍵を一度読み込ませると、以降は自動で署名処理されます。
# Agent 起動
eval "$(ssh-agent -s)"
# → Agent pid 12345
# 鍵を追加(パスフレーズを 1 回入力)
ssh-add ~/.ssh/id_ed25519
# 登録済鍵を確認
ssh-add -l
# 削除
ssh-add -d ~/.ssh/id_ed25519
ssh-add -D # 全削除
# Agent 転送(リモートホストでも自分の鍵を使う)
ssh -A user@bastion
# bastion 上で git pull すれば、自分の PC の鍵で認証される
# ※ セキュリティリスクあり、信頼できるホストのみ
known_hosts と Host Key
# 初回接続時
The authenticity of host 'example.com (192.0.2.1)' can't be established.
ED25519 key fingerprint is SHA256:xxxxxxxxxxxxxxxxxxxxx
Are you sure you want to continue connecting (yes/no)?
# yes と答えると ~/.ssh/known_hosts に記録される
# サーバ再構築でホスト鍵が変わった場合
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
# 古いエントリ削除
ssh-keygen -R example.com
ssh-keygen -R 192.0.2.1
Windows 標準 OpenSSH
Windows 10 (1809) / Windows 11 / Windows Server 2019+ には OpenSSH クライアントが標準搭載。サーバ側は機能追加で有効化できます。
# クライアント
ssh user@example.com # PowerShell / cmd から直接
# サーバ機能の有効化 (管理者 PowerShell)
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
Start-Service sshd
Set-Service -Name sshd -StartupType 'Automatic'
New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server' \
-Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
セキュリティのベストプラクティス
| 項目 | 設定 (/etc/ssh/sshd_config) |
|---|---|
| root 直接ログイン禁止 | PermitRootLogin no |
| パスワード認証無効 | PasswordAuthentication no |
| 公開鍵認証のみ許可 | PubkeyAuthentication yes |
| 空パスワード禁止 | PermitEmptyPasswords no |
| ポート変更 | Port 22022(bot 攻撃低減) |
| 接続元 IP 制限 | firewalld / iptables / AllowUsers |
| 2FA | Google Authenticator PAM モジュール |
| fail2ban | ブルートフォース IP の自動ブロック |
Mosh — 高遅延・断線に強い代替
# Mosh は SSH と互換認証 + UDP ベースの独自プロトコル
# 遅延の大きい回線、モバイル切替時に強い
sudo apt install mosh
mosh user@example.com
FAQ
Q: ssh-agent を毎回起動するのが面倒
A: ~/.bashrc に eval "$(ssh-agent -s)" を入れる、または systemd user service として常駐させる。macOS は keychain 連携で自動。
Q: 多段 SSH を毎回手で踏みたくない
A: ~/.ssh/config の ProxyJump(古い表記は ProxyCommand)でワンライナー化。
Q: 接続がすぐ切れる
A: ServerAliveInterval 60 を設定。間に NAT / firewall がある場合のアイドルタイムアウト対策。