无法在脚本退出时完全关闭远程SSH隧道

时间:2017-07-18 00:32:40

标签: bash ssh ssh-tunnel

我正在编写一个脚本,它从我们远程部署的虚拟机中双向SSH-forwards端口80,并打开这个状态页面"在本地浏览器中。要打开它,SSH隧道必须"后台运行",但是这样做会导致SSH隧道退出,并且我在SSH服务器上保留了持久隧道(bastion )。到目前为止,这是脚本:

#!/bin/sh
# SSH needs a HUP when this script exits
shopt -s huponexit

echo "SSH Forwards the VM status page for a given host..."
read -p "Host Name: " CODE
PORT=$(($RANDOM + 1024))

# "-t -t" (force tty) needed to avoid orphan tunnels on bastion after exit. (Only seems to work when not backgrounded?)
ssh -t -t -4L $PORT:localhost:$PORT user1@bastion sudo ssh -4NL $PORT:localhost:80 root@$CODE.internal-vms &
PID=$!

# Open browser to VM Status Page
sleep 1
open http://localhost:$PORT/

# Runs the SSH tunnel in the background, ensuring it gets killed on shell's exit...
bash

kill -CONT $PID
#kill -QUIT $PID
echo "Killed SSH Tunnel. Exiting..."
sleep 2

不幸的是,考虑到SSH隧道的背景(在第10行使用&),当脚本被杀死(通过CTRL-C)时,"堡垒"服务器最终会无限期地保持孤立的SSH连接。

" -t -t"和" shopt -s huponexit"虽然我已经尝试过了,但我似乎没有帮助。我也在最后kill尝试了各种SIG。我在这做错了什么?谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

-f标志可用于后台处理。要结束连接,ssh -O exit user1@bastion是比kill更好的选择,而且相当暴力。

我会这样做。 Fyi,我没有测试修改过的脚本,虽然我经常使用类似的长SSH命令。<​​/ p>

#!/bin/sh
# SSH needs a HUP when this script exits
shopt -s huponexit

echo "SSH Forwards the VM status page for a given host..."
read -p "Host Name: " CODE
PORT=$(($RANDOM + 1024))

# "-t -t" (force tty) needed to avoid orphan tunnels on bastion after exit. (Only seems to work when not backgrounded?)
ssh -t -t -f -4L $PORT:localhost:$PORT user1@bastion sudo ssh -4NL $PORT:localhost:80 root@$CODE.internal-vms
#PID=$!

# Open browser to VM Status Page
sleep 1
open http://localhost:$PORT/

# Runs the SSH tunnel in the background, ensuring it gets killed on shell's exit...
#bash

#kill -CONT $PID
#kill -QUIT $PID
ssh -O exit user@bastion

echo "Killed SSH Tunnel. Exiting..."
sleep 2