用于本地(非远程)命令执行的ssh隧道 [英] ssh tunnel for local (not remote) command execution

查看:44
本文介绍了用于本地(非远程)命令执行的ssh隧道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个Linux shell(bash-)脚本,该脚本创建SSH隧道,运行使用该隧道的本地命令,最后关闭该隧道和周围的SSH连接.

I want to create a Linux shell (bash-) script which creates an SSH tunnel, runs a local command which uses that tunnel and finally closes the tunnel and the surrounding SSH connection.

为了使解释起来更简单,请考虑对名为"remoteserver"的主机进行本地SSH配置,其中包含不带密码的本地私钥,因此

To make this less difficult to explain consider there is a local SSH configuration to a host called 'remoteserver' containing a local private key without a password, so

ssh remoteserver -L 4444:targetserver:5555

将直接打开与远程服务器的连接,并创建从本地端口4444到目标服务器的隧道.并且考虑到本地命令是 localclient --port 4444 ,脚本将如何打开隧道,执行本地命令并在本地客户端应用程序完成后关闭隧道?

would directly open a connection to the remote server and create a tunnel from the local port 4444 to a target server. And consider the local command would be localclient --port 4444, how would a script look like that opens the tunnel, executes the local command and closes the tunnel after the local client application is finished?

由于应该保持其他并行的正在进行的SSH连接,因此我不希望使用 sudo killall ssh 之类的东西.

As it should be possible to keep other parallel ongoing SSH connections, I don't want something like sudo killall ssh.

推荐答案

您可以尝试类似

TIMEOUT=60 # seconds
ssh remoteserver -L 4444:targetserver:5555 sleep $TIMEOUT &
localclient --port 4444

隧道将在$ TIMEOUT秒后自动关闭.请注意,使用& 仅对无密码连接有效.否则,您需要使用SSH的 -f 标志.

The tunnel will close itself automatically after $TIMEOUT seconds. Note that using the & is only valid with passwordless connections. Otherwise you need to use the -f flag of SSH.

或者,

ssh -N remoteserver -L 4444:targetserver:5555 &
sshpid=$!
localclient --port 4444
kill $sshpid

将在执行 localclient 后立即终止隧道.请注意,这不能与 -f 标志一起使用,因为进程是双叉的.

will kill the tunnel just after localclient executes. Note that this will not work with the -f flag because the process double forks.

这篇关于用于本地(非远程)命令执行的ssh隧道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆