Detect a ssh session
Sometimes I'd like to determine whether current session is a ssh one, so that I can do different things accordingly.
For example,
- set hostname in
$PS1
when connected via ssh, and omit it if connected locally. - use different prefix key for local and remote tmux sessions.
The environment variables defined in ssh sessions
Some SSH related environment variables are set when in a ssh session, so we can tell a ssh session from a local one with that info.
SSH_CONNECTION
Identifies the client and server ends of the connection. The variable contains four space-separated values: client IP address, client port number, server IP address, and server port number.
Example: 10.47.0.50 41284 10.47.0.1 22
Compatibility Notes
OpenSSH
Support for SSH_CONNECTION
is added to OpenSSH in version 3.5 (2002/09/12, in commit f37e24).
Dropbear
Support for SSH_CONNECTION
is added to dropbear in version 0.53 (Thurs 24 February 2011, in commit 4e9f22).
SSH_CLIENT
Identifies the client and server ends of the connection. The variable contains three space-separated values: client IP address, client port number, and server port number.
Example: 10.47.0.50 41284 22
Compatibility Notes
OpenSSH
Support for SSH_CLIENT
is added to OpenSSH in 1999 or earlier (source code).
Dropbear
Support for SSH_CLIENT
is added to dropbear in version 2014.66 (Thursday 23 October 2014, in commit 957450).
Notes
SSH_CLIENT
is very similar to SSH_CONNECTION
, but using this environment variable may lead to some compatibility problem, because
- it's deprecated in favor of
SSH_CONNECTION
; - its support in dropbear is added in October 2014, which may not be available on some old embedded systems.
SSH_TTY
This is set to the name of the tty (path to the device) associated with the current shell or command. If the current session has no tty, this variable is not set.
Example: /dev/pts/0
Compatibility Notes
OpenSSH
Support for SSH_TTY
is added to OpenSSH in 1999 or earlier (source code).
Dropbear
Support for SSH_TTY
is added to dropbear in version 0.53 (Thurs 24 February 2011, in commit ccd025).
Notes
A note for SSH_TTY
is that this variable is not set for a non-interactive shell. So if you want to do something only for an interactive remote shell, SSH_TTY
is a better choice over others. Or if you want to do something as long as current shell is a remote one, you'd better to choose SSH_CONNECTION
.