I'm currently setting up a fairly complex bash configuration which shall be used on multiple machines. I try to find out if it is possible to determine whether I'm logged in via SSH or on a local machine. This way I could, for instance, set some aliases depending on that fact. Like aliasing halt
to restart
since stopping a remote server might not be the best thing to do.
What I know so far is, that the environment variable SSH_CLIENT
is set when I logged in via ssh. Unfortunately, this variable is discarded when I start a super user shell with sudo -s
. I also know that I can pass a parameter to sudo that instructs sudo to copy all my environment variables to the new shell environment, but if I don't want to do this, is there an other way?
You could use "w" or "who" command output. When you connect over ssh, they'll show your source IP.
Here is a great answer I found on unix.stackexchange:
SSH_CLIENT
orSSH_TTY
is defined, it's an ssh session.ps -o comm= -p $PPID
. If it issshd
, it's an ssh session.You could add
SSH_*
toenv_keep
insudoers
so that this can be detected while switched to the other user.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."
If you want to know if you bash shell is directly a child process of sshd (not n>1 layers deep) you can
it should give you
sshd
or whatever is the parent process name of your current shell.Yes, as others noted, the info is in the presence of your IP in parentheses in the output of
who am i
.You can use Bash regular expressions to detect it:
I've came up with the following, based on tips from others here.
It uses a variable for caching - I am using it in my shell theme.
Source:
is_ssh
in https://github.com/blueyed/oh-my-zsh/blob/master/themes/blueyed.zsh-theme#L51-63.All of the other answers work if you are at the first level of login. But if, once login, you run 'su' or 'sudo' (in my case, to switch to a user account without shell for security reasons, I had to run: sudo su - <userid> -s /bin/bash -l), their solution fail.
Following is a universal solution; using pstree, you check for sshd as a parent.
Here is the output of the egrep, when --quiet is removed. It shows the whole hierarchy that matches if one is connected remotely.
If you're on a system that uses logind, then
loginctl
will tell you if the session is remote:However, there are cases that XDG_SESSION_ID is not defined (including after sudo), so I wrote a script to check more things. It tries loginctl, ssh, remote X display and if all fails, connects to logind via D-Bus and attempts to discover the current session by using the current process PID as a key:
Look for your shell's parent cmdline and recurse. Maybe something like the following:
Edited to make it actually work :)