I want to see if I'm connected via ssh or running a local terminal.
If I just ssh into a server without changing to root via sudo
, it's easy. Any of the variables $SSH_CLIENT
, $SSH_CONNECTION
or $SSH_TTY
can be used to check if one is connected via SSH or local.
Problem: When I elevate to the root account with sudo -i
to do administrative stuff, neither of these variables are helpful - they are all empty.
What is the best way to find out if the connection is local or via SSH then?
EDIT: With the accepted answer, it is easy to have an unobtrusive bash prompt which reflects ssh status and privileges:
if [ "$color_prompt" = yes ]; then
# when system is accessed via SSH, hostname with light grey background
if [[ $(pstree -s $$) = *sshd* ]]; then sshbg="\[\033[48;5;7m\]"; fi
# when used as root, change username to orange and '#' to red for prompt
if [ $(id -u) -eq 0 ]; then usercol="\[\033[38;5;3m\]"; hashcol="\[\033[38;5;1m\]"; else usercol="\[\033[38;5;2m\]"; fi
# bash PS1 prompt
PS1="${usercol}\u\[$(tput sgr0)\]@\[$(tput sgr0)\]\[\033[38;5;4m\]${sshbg}\h\[$(tput sgr0)\]:\[$(tput sgr0)\]\[\033[38;5;6m\]\w\[$(tput sgr0)\]${hashcol}\\$ \[$(tput sgr0)\]"
unset sshbg rootcol hashcol
fi
The timed version of the pstree
part runs in less than 20ms, so it can be used without introducing noticeable delays.
If you're in a bash shell, you can do
pstree -s $$
($$ is the current shell's PID) and look for "sshd" in the output.You can also use:
If it says pts/0, pts/1 etc. you're on SSH, if it says tty1, tty2 etc. you're on a local connection.
When I connect using SSH I get the following from
who am i
:Maybe the IP address can also be used as an indicator to differentiate an SSH connection from a local connection on the desktop.
Also explained here: How to check which tty am I currently using?.