退出時的 SSH LocalCommand

退出時的 SSH LocalCommand

每當您透過 SSH 連接到遠端電腦時,您都~/.ssh/config可以使用該LocalCommand指令執行本機命令。但是當我出口SSH 連線?當連線結束或關閉時,似乎不會取得 *.bashrc/.bash_profile* 檔案。

答案1

問題中沒有指定您是否希望在本機或遠端電腦上執行此操作。也沒有指定哪台機器上存在哪個 shell,因此我假設bash兩台機器上都存在。

如果您想在遠端電腦上執行它,請查看~/.bash_logout,它是在登入 shell 正常登出時執行的。從man bash

當登入 shell 退出時,bash 會從該檔案讀取並執行命令~/.bash_logout(如果存在)。

您可以進行測試~/.bash_logout以檢查已註銷的 shell 是否是 SSH 會話,如下所示應該可以工作:

if [[ $SSH_CLIENT || $SSH_CONNECTION || $SSH_TTY ]]; then
    # commands go here
fi

如果您想在本機電腦上執行它,請建立一個函數包裝器ssh。像下面這樣的東西應該​​有效:

ssh() {
    if command ssh "$@"; then
        # commands go here
    fi
}

這對於您的需求來說可能太簡單了,但您明白了。

答案2

你走在正確的軌道上。如果ssh會話是登入 shell(而不是遠端命令),bash則會在登出 shell 時/etc/bash.logout取得來源。~/.bash_logout

如果你想執行遠端命令,那麼你可以強製bash成為登入shell。可能LocalCommand與此類似:

bash -l -c /execute/some/command

man 1 bash

-c string   If  the  -c  option  is  present, then commands are read from 
string.  If there are arguments after the string, they are assigned to 
the positional parameters,  starting with $0.
-l   Make bash act as if it had been invoked as a login shell 

When  a login shell exits, bash reads and executes commands from the 
files ~/.bash_logout and /etc/bash.bash_logout, if the files exists.

相關內容