How to determine if I'm logged in via SSH?

Solution 1:

You could use "w" or "who" command output. When you connect over ssh, they'll show your source IP.

Solution 2:

Here is a great answer I found on unix.stackexchange:


  • If one of the variables SSH_CLIENT or SSH_TTY is defined, it's an ssh session.
  • The login shell's parent process can be checked with ps -o comm= -p $PPID. If it is sshd, it's an ssh session.
if [ -n "$SSH_CLIENT" ] || [ -n "$SSH_TTY" ]; then
  SESSION_TYPE=remote/ssh
else
  case $(ps -o comm= -p $PPID) in
    sshd|*/sshd) SESSION_TYPE=remote/ssh;;
  esac
fi

Solution 3:

You could add SSH_* to env_keep in sudoers so that this can be detected while switched to the other user.


Solution 4:

If you want to know if you bash shell is directly a child process of sshd (not n>1 layers deep) you can

cat /proc/$PPID/status | head -1 | cut -f2

it should give you sshd or whatever is the parent process name of your current shell.


Solution 5:

I think you want to rethink the way you're thinking of the problem. The question isn't "am I logged in via SSH, because I want to turn off certain commands." It's "am I logged in at the console, because then I will enable certain commands."

Tags:

Linux

Shell

Ssh