【问题标题】:How to dynamically change the host in the SSH config file?如何动态更改 SSH 配置文件中的主机?
【发布时间】:2021-11-05 22:00:49
【问题描述】:

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

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

然后我有这个ssh config 文件:

Host MyHost
    ProxyCommand ~/.ssh/vm-connect

它指向一个脚本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)

如果我只运行脚本,它会成功连接到 VM。但如果我运行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

【问题讨论】:

    标签: ssh ssh-config


    【解决方案1】:

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

    这里是它的链接: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"
    

    然后只需从位于~/.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
    

    我添加了CheckHostIP no,这样当IP 地址与known_hosts 中存储的IP 地址不同时,ssh 就不会发出警告。这是可选的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      • 2015-11-30
      • 2013-06-27
      相关资源
      最近更新 更多