在 ssh 打开隧道后运行命令

在 ssh 打开隧道后运行命令

我想要运行一些需要打开 ssh 隧道的进程。

如何运行一些命令ssh 隧道是否成功打开?计时器不够好,因为网络速度和远程机器负载可能会严重影响打开连接所需的时间……

--更新--我想打开隧道并在当地的机器

答案1

您可以使用 LocalCommand ssh 选项,但是有一些限制。来自man ssh_config

LocalCommand

Specifies a command to execute on the local machine after successfully connecting
to the server.  The command string extends to the end of the line, and is
executed with the user's shell.  The following escape character substitutions
will be performed:
  ‘%d’ (local user's home directory),
  ‘%h’ (remote host name), ‘%l’ (local host name),
  ‘%n’ (host name as provided on the command line),
  ‘%p’ (remote port),
  ‘%r’ (remote user name) or ‘%u’ (local user name).

The command is run synchronously and does not have access to the session of
the ssh(1) that spawned it. It should not be used for interactive commands.

This directive is ignored unless PermitLocalCommand has been enabled.

以下是简单示例:

ssh -v -o PermitLocalCommand=yes -o 'LocalCommand=/bin/date >/tmp/test' localhost

稍后,您可能需要将这些选项放入$HOME/.ssh/config文件中适当的主机部分。

答案2

ssh -fN一旦建立连接,将导致 SSH 客户端自行进入后台,因此您应该可以等待该过程,然后执行该命令。

相关内容