I just had the same problem in Linux, using Bash. I first used the environment variable SSH_CONNECTION, but then realized that it is not set if you su -
.
The lastlog solution above didn't work either after su
or su -
.
Finally, I am using who am i
, which shows the remote IP (or the hostname) at the end if it's an SSH connection. It also works after su.
Using Bash regular expressions, this works:
if [[ $(who am i) =~ \([-a-zA-Z0-9\.]+\)$ ]] ; then echo SSH; else echo no; fi
If zsh doesn't support regular expressions, the same can be achieved in many different ways with grep, cut, sed, or whatever.
For the curious, below is what I use this for, in root's .bashrc :
# We don't allow root login over ssh.
# To enable root X forwarding if we are logged in over SSH,
# use the .Xauthority file of the user who did su
w=$(who am i)
if [[ $w =~ \([-a-zA-Z0-9\.]+\)$ ]] ; then
olduser=${w/ .*/}
oldhome=$(getent passwd $olduser | cut -d: -f 6)
[ -f "$oldhome/.Xauthority" ] \
&& export XAUTHORITY=$oldhome/.Xauthority
fi
An alternative which also works with su
would be to recursively search for sshd
through the parent processes:
#!/bin/bash
function is_ssh() {
p=${1:-$PPID}
read pid name x ppid y < <( cat /proc/$p/stat )
# or: read pid name ppid < <(ps -o pid= -o comm= -o ppid= -p $p)
[[ "$name" =~ sshd ]] && { echo "Is SSH : $pid $name"; return 0; }
[ "$ppid" -le 1 ] && { echo "Adam is $pid $name"; return 1; }
is_ssh $ppid
}
is_ssh $PPID
exit $?
If the function is added to .bashrc, it can be used as if is_ssh; then ...
.profile
. And what does this have to do with agent forwarding? – Gilles 'SO- stop being evil' Apr 14 '14 at 20:41eval $(ssh-agent)
but only if i've connected over ssh. i need both the ssh-agent process and the env vars right? – underrun Apr 15 '14 at 18:36SSH_AUTH_SOCK
variable. But why would you run an SSH agent in that case? Did you mean start an agent if you're logged in without agent forwarding? Why not start an agent if there isn't already one ([ -n "$SSH_AUTH_SOCK" ] || eval $(ssh-agent)
)? – Gilles 'SO- stop being evil' Apr 15 '14 at 19:11SSH_CLIENT
andSSH_TTY
to be set but for the parent process to not be sshd and vice-versa? – Praxeolitic Mar 07 '17 at 20:53SSH_*
variables are also set in subprocesses of a shell that's at the head of an SSH session, for example if you start a screen session over SSH (you should unset the variables before starting the session if you care). I think the reason for testing the parent process is that I started doing that before sshd defined any environment variables. – Gilles 'SO- stop being evil' Mar 07 '17 at 21:02