TransWikia.com

Is it possible to check if a connection is local or via ssh *after* elevating to the root account with `sudo`?

Ask Ubuntu Asked by emk2203 on February 18, 2021

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="[33[48;5;7m]"; fi
    # when used as root, change username to orange and '#' to red for prompt
    if [ $(id -u) -eq 0 ]; then usercol="[33[38;5;3m]"; hashcol="[33[38;5;1m]"; else usercol="[33[38;5;2m]"; fi
    # bash PS1 prompt
    PS1="${usercol}u[$(tput sgr0)]@[$(tput sgr0)][33[38;5;4m]${sshbg}h[$(tput sgr0)]:[$(tput sgr0)][33[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.

2 Answers

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.

Correct answer by Brian Turek on February 18, 2021

You can also use:

who am i | awk -F' ' '{print $2}'

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:

am       pts/0        2020-08-28 12:33 (172.17.0.5)

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?.

Answered by Artur Meinild on February 18, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP