SSH (Secure Shell) 是 Linux 遠端管理的核心服務。本文從安裝確認、服務啟動、連接埠修改、防火牆開放到遠端連線測試,提供完整的 SSH 服務配置流程。
# 檢查是否已安裝
rpm -qa | grep ssh
# 或
dpkg -l | grep openssh
# 未安裝時安裝
yum install openssh-server openssh-clients # CentOS/RHEL
apt-get install openssh-server openssh-client # Ubuntu/Debian
# System V init
service sshd start
/etc/init.d/sshd start
# systemd (CentOS 7+, Ubuntu 16.04+)
systemctl start sshd
systemctl enable sshd # 開機自啟
vi /etc/ssh/sshd_config
| 參數 | 預設值 | 建議值 | 說明 |
|---|---|---|---|
| Port | 22 | 2222 (或其他 >1024) | 修改預設埠降低自動掃描攻擊,**修改後需重啟服務並更新防火牆** |
| PermitRootLogin | yes | prohibit-password | 禁止密碼登入 root,僅允許金鑰 |
| PubkeyAuthentication | yes | yes | 啟用公鑰認證 |
| PasswordAuthentication | yes | no (配合金鑰) | 禁用密碼認證提升安全 |
| MaxAuthTries | 6 | 3 | 限制嘗試次數 |
| AllowUsers | (無) | user1 user2 | 白名單限制可登入使用者 |
| ClientAliveInterval | 0 | 300 | 5 分鐘無活動發送保持封包 |
| ClientAliveCountMax | 3 | 2 | 失敗 2 次斷開 |
注意:修改 Port 時,前面的 # 必須移除以生效。
# iptables
iptables -A INPUT -p tcp --dport 2222 -j ACCEPT
service iptables save
# firewalld (CentOS 7+)
firewall-cmd --permanent --add-port=2222/tcp
firewall-cmd --reload
# ufw (Ubuntu)
ufw allow 2222/tcp
ufw enable
# 密碼登入
ssh -p 2222 user@server_ip
# 金鑰登入
ssh -p 2222 -i ~/.ssh/id_rsa user@server_ip
# Windows 使用 PuTTY/Xshell/MobaXterm 指定埠號連線
AllowUsers, AllowGroups)/var/log/secure 或 /var/log/auth.log