I want to run a command every time I log in to my Ubuntu box, but only if I'm connecting through telnet, not if I'm logging in at the console.
3 Answers
Something like this in your .bashrc (assuming bash) should work fairly well:
if ( tty | egrep -q '\/pts\/' )
then
echo "is a pts - remote login"
else
echo "is not a pts - local login"
fi
You would just replace the echo's with whatever it was that you wanted to run.
telnet? I don't recommend its use! One of the following approaches should work for most methods of remote access. (Remote access via a X client, or via VNC or similar being excusable exceptions.)
- some
telnetd
set the environment variableREMOTEHOST
or similar which you can check - if you are running
xinetd
you can alter thetelnetd
environment via theenv
attribute - if you really mean
ssh
(OpenSSH), then you can check either of the variablesSSH_TTY
andSSH_CONNECTION
.
The Linux console virtual terminals (before you start X) will have tty names like /dev/tty1
rather than pty (pseudo-ttys) in /dev/pts/
(at least on x86). Within X, terminals will be allocated ptys.
Checking environment variables can often be subverted by users, if that's a concern.
A more robust general case solution is to walk up the process tree from $$, until you find what you're looking for (or not), use this in a bash
script:
function checkparents()
{
local _proc=$1 _pid _ppid=$$ _tty="" _comm _rc=1
while [ "$_ppid" != "1" ]; do
read _pid _ppid _tty _comm < <(ps --no-headers -p $_ppid -o "pid ppid tty comm")
#echo "$_pid $_ppid $_tty $_comm"
[ "$_comm" = "$_proc" ] && { _rc=0; break; }
[ "$_pid" = "$_proc" ] && { _rc=0; break; }
done
return $_rc
}
When run via an ssh
login for example:
$ if checkparents sshd; then echo ssh; fi
ssh
$ if ! checkparents in.telnetd; then echo not telnet; fi
not telnet
Un-comment the echo
line to see it working.
I personally munge the output of "who am i" for other reasons (setting DISPLAY). The last field seems to be the "source" of the login
typeset -a LOGINARRAY
# who am I format: USER TTY MON DAY TIME LOGINHOST,
# use array to get last entry
LOGINARRAY=( $(/usr/bin/who -sum) )
LASTINDEX=$(( ${#LOGINARRAY[*]} - 1))
LOGINHOST=${LOGINARRAY[$LASTINDEX]}
LOGINHOST=${LOGINHOST##*\(}
LOGINHOST=${LOGINHOST%%)*}
DISPLAY=$LOGINHOST:0
export DISPLAY
unset LOGINARRAY LASTINDEX
it should be easy enough to check the format of LOGINHOST to see if it's a "remote" login. telnet is disabled here (as it should be) so I can't explicitly check to see how it's set for telnet