返回上一頁

Ubuntu Server SSHD 設定

公司的 VM 的 Ubuntu 主機看起來預設是沒開 sshd 的, 要自己開

透過 apt-get 安裝

sudo apt-get update
sudo apt-get install ssh openssh-server

調整 sshd 設定

sudo nano /etc/ssh/sshd_config

做以下調整

Port 22
PermitRootLogin no          # 禁止 root 直接登入
PasswordAuthentication yes   # 完成金鑰登入後再改成 no 關閉
PubkeyAuthentication yes
PermitEmptyPasswords no
UsePAM yes

Ubuntu 的 ssh 服務預設為 disabled, 可設定自動啟用

sudo systemctl enable ssh

重啟 sshd 服務

sudo systemctl restart sshd

設定 SSH 金鑰登入

在本機端產生金鑰對 (若已有可跳過此步驟)

ssh-keygen -t ed25519 -C "gary@dev.example.com" -f server_logon_key
# 若不支援 ed25519 可改用 rsa

此時會在當前目錄產生兩個檔案, 一個是 server_logon_key (Private Key), 另一個是 server_logon_key.pub (Public Key)

將 Public Key 複製到 Ubuntu Server 上

echo "your_public_key_content(server_logon_key.pub)" >> ~/.ssh/authorized_keys

確認可用 SSH 金鑰登入之後, 可將 sshd_config 裡的 PasswordAuthentication 改成 no 以強化安全性

sudo nano /etc/ssh/sshd_config
PasswordAuthentication no # 關閉密碼登入

關閉密碼登入會影響 Web Console 的使用, 自行斟酌

Client 端設定

使用 VS Code Remote-SSH 套件連線

Ctrl+Shift+P 開啟指令面板, 輸入 Remote-SSH: Open Configuration File 編輯 config 檔案, 加入以下內容

Host `主機別名`
    HostName `domain_or_ip_address`
    User ubuntu
    IdentityFile /path/to/private_key_file

之後可以在 Remote-SSH: Connect to Host... 指令中指定 主機別名 來連線至這個設定好的主機

有設定 SSH 金鑰登入並成功的情況, 登入過程中不會詢問密碼, 反之則會要求輸入密碼