bash - 无法完全关闭脚本导出中的远程SSH隧道

标签 bash ssh ssh-tunnel

我正在编写一个脚本,该脚本从我们远程部署的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/

相关文章:

linux - 有没有办法限制进程在启动时消耗的内存

python - 以编程方式在 dockerized apache Airflow python 操作符内创建 SSH 隧道

bash - 删除列的一部分,如果它在特定的列号中。 (该列有一个变量)

linux - 如何添加到 rsynced tar 备份

perl - 使用 Net::SSH::Perl 登录远程机器

linux - 如何在 github 上为 1 个用户的 2 个 repo 添加部署 key

mysql - BASH:SSH 进入服务器,查询 MYSQL 有趣的东西

linux - tsocks 不隧道到 ssh

Java:SSH隧道-设置本地SOCKS作为监听器

linux - bash中间接引用数组的访问范围