WSL 安裝 ssh 並更改 port 設置自動啟動
預設狀態是不會自動啟動的而且 port 可能與主機端有衝突,視情況可以自行改成 2222 口這樣可以避開 Windows 本身如果也有 ssh 的話。
安裝並配置 OpenSSH
首先,確保已安裝 OpenSSH 伺服器:
sudo apt update
sudo apt install openssh-server
1. 設定 SSH 端口與密碼登入
編輯 SSH 設定檔:
sudo nano /etc/ssh/sshd_config
- 找到
Port
行,並修改為你所要的或保持預設就 22 - 找到
PasswordAuthentication
行,並修改為 yes
Port 22
PasswordAuthentication yes
儲存並退出 (Ctrl+S
然後 Ctrl+X
)。
這裡預設值其實本來就是 22 ,只是為了示範如何修改而特地寫出來
2. 設定 SSH 伺服器開機自動啟動
設置 systemd 服務管理器:
sudo systemctl enable ssh
必須開著 WSL 視窗才會生效(這服務 systemctl 其實是由 wsl.conf 文件間接啟動的)
如果是舊版的 wsl 不支持 systemctl 請這裡編輯 /etc/wsl.conf 文件:
sudo nano /etc/wsl.conf
在文件末尾添加以下內容:
command="service ssh start"
保存文件(按 Ctrl + O),然後退出編輯器(按 Ctrl + X)。
4. 重啟 WSL
在 Windows 命令提示字元或 PowerShell 中執行:
wsl --shutdown
然後再次打開 WSL 後,SSH 伺服器應該會自動啟動並使用設定的端口。
sudo service ssh status
從主機端以 SSH 連接 WSL
ssh -p 22 your_username@localhost
這裡 -p 的選項預設值就是 22,如果沒有改 port 可以省略不打
[番外篇] 在 WSL 中添加允許的公鑰
在 WSL 中創建 .ssh
目錄並設置適當的權限:
mkdir -p ~/.ssh
chmod 700 ~/.ssh
已經存在則無需建立
將你想要使用的公鑰添加到 authorized_keys
文件中:
nano ~/.ssh/authorized_keys
已經存在則無需建立
將公鑰貼上到此文件中,然後保存並退出。設置 authorized_keys
文件的權限:
chmod 600 ~/.ssh/authorized_keys