Is it possible to tell if a terminal is SSH'd into a machine ? some kind of command to do this for me and execute something if I am SSHd?
Asked
Active
Viewed 3,213 times
3 Answers
21
You can check if the $SSH_CLIENT
and the $SSH_TTY
variables are set:
(through SSH) $ [[ -z $SSH_TTY ]]; echo $?
1
(local) $ [[ -z $SSH_TTY ]]; echo $?
0
The $SSH_CLIENT
variable contains the IP you're connecting from, along with the remote and the local port:
(through SSH) $ echo $SSH_CLIENT
15.3.25.189 54188 22

Josh The Geek
- 1,159

runejuhl
- 583
6
Try pressing Enter then pressing ~?.
If you're using an OpenSSH client you should receive a list of supported escape sequences which perform miscellaneous functions.
$ ~?
Supported escape sequences:
~. - terminate connection (and any multiplexed sessions)
~B - send a BREAK to the remote system
~C - open a command line
~R - request rekey
~V/v - decrease/increase verbosity (LogLevel)
~^Z - suspend ssh
~# - list forwarded connections
~& - background ssh (when waiting for connections to terminate)
~? - this message
~~ - send the escape character by typing it twice
(Note that escapes are only recognized immediately after newline.)
This will validate the connected state on the local machine as opposed to checking environment variables which are set on the remote machine and, thus, subject to remote configuration.

vschum
- 638
-
1careful, on some OpenSSH clients, this terminates the ssh connection! – Olivier Dulac Sep 04 '14 at 11:16
-
~ by itself does not do anything for me. The two-letter sequences as in http://lonesysadmin.net/2011/11/08/ssh-escape-sequences-aka-kill-dead-ssh-sessions/ work. – Emil Jeřábek Sep 04 '14 at 15:51
-
-
1I'd rather use
$?
. This answer is in a way complementary to the others currently present since this detects the connected state on the local machine while checking environment variables is a test run on the remote machine (and subject to remote configuration). – MvG Sep 04 '14 at 19:47 -
2
There are the $SSH_CLIENT
and $SSH_CONNECTION
variables, but if you use a program like screen
, these variables will remain set though they are obsolete. If this matters, you may want to use my escreen
and sh.screen
utilities.

vinc17
- 12,174
(env -i PATH="$PATH" /bin/bash some-script </dev/null >/dev/null 2>&1 &)
- env -i to remove any environmental hints, subshell to make sure it re-parents to init ASAP instead of the shell under ssh, and redirections so that it can't be associated with the TTY. There are probably other tracks that can be covered too. – Score_Under Sep 03 '14 at 23:32