Bash脚本设置临时SSH隧道 [英] Bash script to set up a temporary SSH tunnel
问题描述
在Cygwin上,我希望Bash脚本能够:
On Cygwin, I want a Bash script to:
- 创建到远程服务器的SSH隧道.
- 在本地使用隧道进行一些工作.
- 然后关闭隧道.
关机部分让我感到困惑.
The shutdown part has me perplexed.
目前,我有一个me脚的解决方案.在一个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)
最后,完成后,我关闭第一个外壳窗口以杀死隧道.
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.
这篇关于Bash脚本设置临时SSH隧道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!