
我正在嘗試使用 shell 腳本從跳轉伺服器將 ssh 金鑰傳送到多個伺服器。我只能從我的 ad 帳號登錄,然後切換到 root,無法直接以 root 身分登入。遇到這種情況,我如何將 ssh 金鑰傳送到需要在 /root/.ssh/authorized-keys 下複製的伺服器?
答案1
您無需成為跳轉伺服器上的 root 即可以 root 身分存取其他伺服器。
如果您還沒有 ssh 設定文件,請先建立一個。它通常存在於~/.ssh/config
(其中 ~ 是 $HOME 的簡寫)。
您首先需要了解的一些事情是您嘗試從跳轉伺服器存取的伺服器的 IP 範圍。希望這些 IP 與跳轉伺服器不在同一子網路中。
這是一個範例:
# save as ~/.ssh/config
CheckHostIP no
StrictHostKeyChecking no
AddKeysToAgent yes
ForwardAgent yes
UserKnownHostsFile /dev/null
# Servers to get to via jump server
# (note their subnet defined by a range using an asterisk, you need to provide)
# This establishes root as login id for every server in the range
# and uses the JumpServer (can leave that name as is) as a proxy.
Host 192.168.122.*
ProxyJump JumpServer
User root
# JumpServer info. Provide its IP or FQDN and your user id
# IP or FQDN set in the HostName; you can leave Host set as JumpServer
# since this is referred to above in ProxyJump line
Host JumpServer
HostName ip-or-fqdn-of-jumpserver
User your-user-id
在上述範例中,您只需針對您的環境進行 3 項變更:
- 替換
192.168.122.*
為您的伺服器 IP 範圍 - 替換
ip-or-fqdn-of-jumpserver
為您的跳轉伺服器 IP 或 FQDN(完全限定網域名稱) - 替換
your-user-id
為您用於 ssh 存取的跳轉伺服器上的使用者 ID
建立該檔案後,您可以透過下面所示的命令將公鑰放入每個伺服器的根authorized_keys 檔案中ssh-copy-id
。當然,第一次您可能需要提供憑證。
此外,預設情況下,大多數伺服器都配置為不允許直接進行 ssh root 存取。如果是這種情況,您需要在每台伺服器上進行更多 sshd_config 變更。
現在只需運行ssh-copy-id 192.168.122.10
即可將您的公鑰複製到伺服器上的根authorized_keys 檔案中。當然將IP替換為你自己的伺服器IP。對每個伺服器重複此操作。
一旦金鑰出現在每台伺服器上,您現在應該能夠ssh some-server-IP
使用您的使用者 ID 自動建立到跳轉伺服器的連接,並建立連接埠轉送以便以 root 身分存取遠端伺服器。