I would like to detect whether the current user session is from an SSH connection - that is, whether the user is physically sitting at the computer that hosts the current terminal or whether he is remotely connected through SSH?

Is there an easy way to do this, preferably through a bash-scriptable method?

share|improve this question
    
you might want to check out this U&L question: unix.stackexchange.com/questions/9605/… – muru Oct 18 '14 at 4:20
up vote 1 down vote accepted

A quick way would be check if the SSH_TTY variable is set:

$ ssh lab
$ echo $SSH_TTY 
/dev/pts/22

There are a few SSH-related variables set. Two others are SSH_CLIENT and SSH_CONNECTION. Either of them could be used as well.


Another way would be to check if an ancestor process is the sshd daemon:

$ pstree -ps $$
init(1)───sshd(1170)───sshd(14153)───sshd(14225)───bash(24232)───pstree(27281)

Relevant reading:

share|improve this answer
1  
Excellent. This is exactly what I was looking for. I'll keep the question open for a few days, and then if this is still the best answer then I'll accept it. – fouric Oct 18 '14 at 4:13
    
@InkBlend sure. I personally use the SSH_TTY variable to set custom prompts for SSH sessions. – muru Oct 18 '14 at 4:14

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.