![如何使用跳轉伺服器提供的可變主機名稱設定 SSH 連接](https://rvso.com/image/789293/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%E8%B7%B3%E8%BD%89%E4%BC%BA%E6%9C%8D%E5%99%A8%E6%8F%90%E4%BE%9B%E7%9A%84%E5%8F%AF%E8%AE%8A%E4%B8%BB%E6%A9%9F%E5%90%8D%E7%A8%B1%E8%A8%AD%E5%AE%9A%20SSH%20%E9%80%A3%E6%8E%A5.png)
我想為需要連接到登入節點(跳轉伺服器)的情況建立一個 .sshconfig 文件,透過執行命令從該節點取得主機名,然後使用與我相同的使用者名稱和憑證 ssh 到該主機名稱用於登入節點。這是我最終得到的配置:
Host jump-server
HostName loginnode
User user
Host remote
User user
IdentityFile C:\Users\user\.ssh\id_rsa
ForwardX11 yes
ForwardX11Trusted yes
XAuthLocation /usr/bin/xauth
ProxyCommand ssh -q jump-server "ssh user@`command_to_get_the_hostname` bash -l"
我正在嘗試使用以下命令進行 ssh:
ssh.exe -v remote
我得到這個輸出:
OpenSSH_for_Windows_8.1p1, LibreSSL 3.0.2
debug1: Reading configuration data C:\\Users\\user/.ssh/config
debug1: C:\\Users\\user/.ssh/config line 14: Applying options for remote
debug1: Executing proxy command: exec ssh -q jump-server "ssh lemoni15@`command_to_get_the_hostname` bash -l"
debug1: identity file C:\\Users\\user\\.ssh\\id_rsa type 0
debug1: identity file C:\\Users\\user\\.ssh\\id_rsa-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_for_Windows_8.1
: command not foundSH_for_Windows_8.1
答案1
RemoteCommand
你說只有跳轉主機知道遠端主機的主機名,對嗎?它ProxyCommand
在本機電腦上運行,因此它永遠不會command_to_get_the_hostname
在跳轉主機上運行。為了首先連接到跳轉主機,然後在那裡運行命令,您可以使用RemoteCommand
。
RemoteCommand
指定成功連接到伺服器後在遠端電腦上執行的命令。命令字串延伸到行尾,並使用使用者的 shell 執行。 - -
例如
Host remote
Hostname jump-host.example.com
User user
RemoteCommand ssh user@$(/full/path/to/command_to_get_the_hostname)
現在您可以使用連接到遠端主機ssh -t remote
,其中-t
強制偽終端分配$(command)
用於在遠端(即跳轉主機上)運行。
作為副作用,您將無法使用IdentityFile C:\Users\user\.ssh\id_rsa
遠端主機的本機金鑰,但跳轉主機必須擁有金鑰,因為第二個主機ssh
現在正在跳轉主機上執行。
ProxyJump
& 腳本編寫
如果您想將跳轉主機用作ProxyJump
( -J
) 主機,能夠使用本機IdentityFile
( -i
)、ForwardX11
( -X
)、ForwardX11Trusted
( -Y
) 等,則需要編寫一些腳本,而不僅僅是使用 SSH 設定檔。您首先需要連接到跳轉主機,從那裡取得遠端主機位址,然後在另一個 SSH 連線中使用它。
和重擊這會是這樣的:
#!/bin/bash
remotehost=$(\
ssh [email protected] \
/full/path/to/command_to_get_the_hostname) || exit 1
ssh -X -Y -J [email protected] \
-i ~/.ssh/id_rsa user@"$remotehost"
我思考這可以變成電源外殼Windows 上的腳本(未測試):
$remoteHost = ssh.exe [email protected] `
/full/path/to/command_to_get_the_hostname
if (-not $?) {throw "Failed to get the remote hostname"}
ssh.exe -X -Y -J [email protected] `
-i "C:\Users\user\.ssh\id_rsa" "user@$remoteHost"