SSH(Secure Shell)為遠端登入與其他網路服務提供加密通道,能防止管理過程中的資料外洩,也能抵禦 DNS 欺騙與 IP 欺騙;由於傳輸內容會壓縮,速度也比你想像的快。
用戶端有兩種驗證等級:密碼驗證只要有帳號密碼就能登入且全程加密,但無法排除伺服器被冒名,仍有中間人攻擊風險;金鑰驗證則要求你產生一組公私鑰,把公鑰放在目標伺服器上,伺服器以公鑰加密「質詢」回傳,用戶端以私鑰解密回應,能確實排除中間人。
伺服器端同樣有兩種方案:一是主機把公鑰分發給用戶端,用戶端用它加密資料、主機以私鑰解密,藉此確認對方身份;二是設置金鑰認證中心,所有主機提交公鑰給中心,用戶端只需保存中心的公鑰。
實驗環境:

(1)用戶端 若用戶端是 Windows,可用 SecureCRT 產生 SSH2 金鑰:Options → Global Options → SSH2,選擇產生新金鑰(RSA 或 DSA 皆可),一路下一步並設定金鑰保護密碼。







完成後會在 C:\Users\Administrator\AppData\Roaming\VanDyke\ 產生名為 Identity 的公鑰與私鑰。
(2)伺服器端 為了安全,關掉空密碼與密碼登入。編輯 /etc/ssh/sshd_config(Red Hat 實際檔名是 sshd_config,不是 sshd.conf):
PermitEmptyPasswords no
PasswordAuthentication no
重啟 sshd 生效。首次以 ssh localhost 連線會要求確認主機指紋,輸入 yes 後該主機會被寫入 ~/.ssh/known_hosts。
接著用 rz 把用戶端的 Identity.pub 上傳到 ~/.ssh,合併進 authorized_keys 並收緊權限:
[root@viong .ssh]# cat Identity.pub >> authorized_keys
[root@viong .ssh]# rm -rf Identity.pub
[root@viong .ssh]# chmod 400 authorized_keys
重新連線時會要求輸入金鑰密碼,即代表設定成功。
Client 192.168.15.50 → Server 192.168.15.64。在用戶端產生金鑰時,存檔位置與密碼都直接按 Enter:
[root@client .ssh]# ssh-keygen –t rsa
接著用 ssh-copy-id 把公鑰發布到伺服器(會自動建立 ~/.ssh/authorized_keys):
[root@client .ssh]# ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.15.64
若對方 SSH 不是 22 埠(例如 2520),要補上 -p:
ssh-copy-id -i /root/.ssh/id_rsa.pub “-p 2520 192.168.15.64”
伺服器端確認 authorized_keys 已生成且內容正確後,用戶端直接 ssh root@192.168.15.64 即可免密碼登入。
易踩的坑:ssh-keygen 問「Enter file in which to save the key」時若自行輸入檔名,後續免密登入會出現 Permission denied (publickey,gssapi-with-mic),所以請直接 Enter,事後再改名。
金鑰沒有保護密碼時,也能順便用 scp 做加密備份(scp 基於 ssh):
[root@clinet .ssh]# scp id_dsa.pub root@192.168.15.64:/home/ <本機 → 遠端>
[root@server home]# scp id_dsa.pub root@192.168.15.50:/home/ <遠端 → 本機>
(1)伺服器端(AS5)同樣修改 /etc/ssh/sshd_config 的 PermitEmptyPasswords 與 PasswordAuthentication 並重啟 sshd。首次 ssh localhost 登入後,主機公鑰會寫進 known_hosts。
接著在伺服器產生 DSA 金鑰並自行使用:
[root@viong .ssh]# ssh-keygen -t dsa
[root@viong .ssh]# cat viong.pub >> authorized_keys
[root@viong .ssh]# chmod 400 authorized_keys
(2)用戶端(Win 7 + SecureCRT)用 sz 把私鑰與公鑰都抓回本機同一目錄,伺服器端再刪除這兩個檔案:
[root@viong .ssh]# sz viong
[root@viong .ssh]# sz viong.pub
用 SecureCRT 指定該私鑰連線,成功即完成。

Port 22(可重複設定多個埠)、Protocol 2,1(同時支援 v1/v2)、ListenAddress(限定監聽的介面)、LoginGraceTime 600(登入逾時秒數)、Compression yes。
HostKey 指定 v1 的 ssh_host_key 與 v2 的 rsa/dsa 私鑰;KeyRegenerationInterval 與 ServerKeyBits 屬 v1 專用。
SyslogFacility AUTH(日誌寫入 /var/log/secure)、LogLevel INFO。
安全相關:PermitRootLogin no(不建議開放 root 直接登入)、StrictModes yes(主機金鑰變動就拒絕連線,可擋部分木馬)、PubkeyAuthentication yes、AuthorizedKeysFile .ssh/authorized_keys。
認證相關:RhostsAuthentication no、IgnoreRhosts yes、HostbasedAuthentication no、PasswordAuthentication yes、PermitEmptyPasswords no、ChallengeResponseAuthentication yes。
其他:X11Forwarding、PrintMotd no、PrintLastLog yes、KeepAlive yes、UsePrivilegeSeparation yes、MaxStartups 10(未登入連線數上限)、DenyUsers/DenyGroups(黑名單)、Subsystem sftp /usr/lib/ssh/sftp-server。
本文出自 “技術在於折騰” 博客,請務必保留此出處https://viong.blog.51cto.com/844766/278062