2017-07-18 59 views
1

我正在編寫一個腳本,它可以從遠程部署的VM中雙向SSH轉發端口80,並在本地瀏覽器中打開此「狀態頁面」。要打開它,SSH通道必須是「後臺傳輸」,但是這樣做會導致SSH隧道退出,並在隧道中通過的SSH服務器上保留一個持久通道(bastion)。這裏是腳本,到目前爲止:無法完全關閉腳本退出程序中的遠程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 -4L $PORT:localhost:$PORT [email protected] sudo ssh -4NL $PORT:localhost:80 [email protected]$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隧道,當腳本被殺害(通過CTRL-C)(10號線使用&)時,「堡壘」的服務器端的backgrounding孤立的SSH連接保持無限期。

-t -t」和「shopt -s huponexit」是固定的我試過了,但似乎沒有幫助。我還在最後的kill上嘗試過各種SIG。我在這裏做錯了什麼?感謝您的幫助!

+0

遺憾的是,我在這個系統中繼承了一些奇怪的限制。最重要的是需要使用sudo從堡壘到虛擬機ssh。而且有很多虛擬機,因此將user1的SSH密鑰部署到所有虛擬機將會很困難。 – Excalibur

+0

我可以建議Ansible管理您的虛擬機並將密鑰部署到所有虛擬機嗎?這會讓你的生活更加輕鬆,虛擬機更安全。 –

+0

其實,我們現在正在推出Ansible配置管理。 Ansible很棒。不幸的是,有很多遺留服務需要我們一點一點地「整理」。 – Excalibur

回答

1

-f標誌可用於後臺進程。要結束連接,ssh -O exit [email protected]是一個比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 [email protected] sudo ssh -4NL $PORT:localhost:80 [email protected]$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 [email protected] 

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

我已經實現了這個推薦,並做一些修改(ControlPath需要一個套接字,而不是一個普通的文件)然而,在斷開連接後,由sudo調用的第二個連接仍然在Bastion上運行,並且必須在該服務器上手動斷開連接 – Excalibur

+0

我認爲解決方案是以避免使用sudo,因爲它會調用一個新的shell進程,它不會從原始SSH連接接收信號 – Excalibur

+0

'ssh -O exit'需要ControlPath才能工作,您可能需要使用sudo-ed SSH不能退出,因爲它以root身份運行。一種解決方案是在某個時間段後使SSH服務器自動啓動d/c http://www.2daygeek.com/automatically-disconnect-inactive-idle-ssh-sessions/。 –