如何动态更改 SSH 配置文件中的主机?

Dim*_*los 3 ssh ssh-config

我正在尝试连接到 GCP 实例,该实例每次重新启动时都会更改其公共 IP。要动态获取 IP,我使用以下gcloud命令:

gcloud compute instances describe <vm-name> --zone europe-west --format='get(networkInterfaces[0].accessConfigs[0].natIP)'
Run Code Online (Sandbox Code Playgroud)

然后我有这个ssh config文件:

Host MyHost
    ProxyCommand ~/.ssh/vm-connect
Run Code Online (Sandbox Code Playgroud)

vm-connect它指向具有以下内容的脚本

#!/bin/bash
get_host() {
    gcloud compute instances describe <vm-name> --zone europe-west1-b --format='get(networkInterfaces[0].accessConfigs[0].natIP)'
}

ssh minikf@$(get_host)
Run Code Online (Sandbox Code Playgroud)

如果我只运行脚本,它就会成功连接到虚拟机。但如果我运行ssh MyHost它会给我:

Pseudo-terminal will not be allocated because stdin is not a terminal.
-bash: line 1: SSH-2.0-OpenSSH_8.2p1: command not found
Run Code Online (Sandbox Code Playgroud)

she*_*ehz 5

我刚刚从另一个答案中解决了这个确切的问题。

这是它的链接:https://superuser.com/questions/1633430/ssh-config-with-dynamic-ip

相关位:

ProxyCommand 充当原始 TCP 连接的替代方案。它不会取代整个 SSH 连接

%p将替换 ssh 的端口,您可以添加IdentityFile和所有其他ssh_config文件选项。

~/.ssh/config添加这些行,这可能对您有用

Host MyHost
    User minikf
    CheckHostIP no
    ProxyCommand bash -c "nc $(~/.ssh/vm-connect) %p"
Run Code Online (Sandbox Code Playgroud)

然后只需从位于的脚本中回显主机地址~/.ssh/vm-connect

#!/bin/bash
get_host() {
    gcloud compute instances describe <vm-name> --zone europe-west1-b --format='get(networkInterfaces[0].accessConfigs[0].natIP)'
}

echo get_host
Run Code Online (Sandbox Code Playgroud)

我已经添加了CheckHostIP no这样的ssh内容,当 IP 地址与存储在known_hosts. 这是可选的。