我正在编写一个脚本,该脚本从我们远程部署的VM双击SSH转发端口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。我在这里做错了什么?感谢您的协助!
最佳答案
-f
标志可用于后台处理。要终止连接,与暴力比较严重的ssh -O exit user1@bastion
相比,kill
是更好的选择。
我会这样做。 Fyi,尽管我经常使用类似的长SSH命令,但我没有测试修改后的脚本。
#!/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
关于bash - 无法完全关闭脚本导出中的远程SSH隧道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45155629/