用于设置临时 SSH 隧道的 Bash 脚本 [英] Bash script to set up a temporary SSH tunnel

查看:25
本文介绍了用于设置临时 SSH 隧道的 Bash 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Cygwin 上,我想要一个 Bash 脚本:

On Cygwin, I want a Bash script to:

  1. 创建到远程服务器的 SSH 隧道.
  2. 在本地做一些使用隧道的工作.
  3. 然后关闭隧道.

关机部分让我很困惑.

目前,我有一个蹩脚的解决方案.在一个 shell 中,我运行以下命令来创建一个隧道:

Currently, I have a lame solution. In one shell I run the following to create a tunnel:

# Create the tunnel - this works! It runs forever, until the shell is quit.
ssh -nNT -L 50000:localhost:3306 jm@sampledomain.com

然后,在另一个 shell 窗口中,我做我的工作:

Then, in another shell window, I do my work:

# Do some MySQL stuff over local port 50000 (which goes to remote port 3306)

最后,当我完成时,我关闭第一个 shell 窗口以终止隧道.

Finally, when I am done, I close the first shell window to kill the tunnel.

我想在一个脚本中完成这一切,例如:

I'd like to do this all in one script like:

# Create tunnel
# Do work
# Kill tunnel

如何跟踪隧道进程,以便知道要杀死哪个进程?

How do I keep track of the tunnel process, so I know which one to kill?

推荐答案

您可以使用 ssh '控制套接字' 干净利落地做到这一点.要与一个已经在运行的 SSH 进程对话并获取它的 pid,杀死它等等.使用控制套接字"(-M 代表主机,-S 代表套接字),如下所示:

You can do this cleanly with an ssh 'control socket'. To talk to an already-running SSH process and get it's pid, kill it etc. Use the 'control socket' (-M for master and -S for socket) as follows:

$ ssh -M -S my-ctrl-socket -fnNT -L 50000:localhost:3306 jm@sampledomain.com
$ ssh -S my-ctrl-socket -O check jm@sampledomain.com
Master running (pid=3517) 
$ ssh -S my-ctrl-socket -O exit jm@sampledomain.com
Exit request sent. 

请注意,my-ctrl-socket 将是一个实际创建的文件.

Note that my-ctrl-socket will be an actual file that is created.

我从 OpenSSH 邮件列表上非常 RTFM 的回复.

这篇关于用于设置临时 SSH 隧道的 Bash 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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