SSH LocalCommand on exit

In ~/.ssh/config you can make use of the LocalCommand instruction to execute a neighborhood command whenever you connect to a remote equipment using SSH. Yet just how do I execute a command when I exit an SSH link? It appears that *. bashrc/. bash_profile * files are not sourced when link finishes or is shut.

9
2022-06-07 14:32:51
Source Share
Answers: 2

You get on the appropriate track. If the ssh session is a login covering (as opposed to a remote command), bash will certainly resource /etc/bash.logout and also ~/.bash_logout when you exit the covering.

If you intend to execute a remote command, after that you can compel bash to be a login covering. The LocalCommand can be comparable to this:

bash -l -c /execute/some/command

From 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.
1
2022-06-07 14:52:39
Source

It is not defined in the inquiry if you desire this implemented on the neighborhood or remote equipment. It is additionally not defined which covering exists on either equipment, so I'm thinking bash for both.

If you intend to execute it on the remote equipment, consider ~/.bash_logout, which is implemented when a login covering logs out beautifully. From man bash:

When a login covering leaves, bash reviews and also implements commands from the documents ~/.bash_logout, if it exists.

You can do an examination in ~/.bash_logout to examine if the covering being logged out of is an SSH session, something like the adhering to need to function:

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

If you intend to execute it on the neighborhood equipment, create a function wrapper around ssh. Something like the adhering to need to function:

ssh() {
    if command ssh "[email protected]"; then
        # commands go here
    fi
}

That might be also straightforward for your demands, yet you understand.

11
2022-06-07 14:52:37
Source