hdrssh

Logged in through ssh?

I've recently come across a problem where I have to check (using bash scripting) whether I am logged in remotely (through ssh, since I only use ssh for that purpose) or locally. This is particularly useful if you have many machines with the same color scheme of bash prompt (and you want to keep it that way), but work on all of them from your local computer.

In this post I'm going to show you how I decided to modify the bash prompt so that I'm sure whether I'm working locally or remotely.

Using the proc filesystem

One of the ways of solving this problem I found somewhere on the Internet is to check the parent process of the current shell. The process id of the parent process is available in the PPID variable. Getting this process' name is as simple as:

Now to test if this process is sshd (which will be the case if the user logged in using ssh), we can use:

However, this approach has one major flaw. The fact that the user logged in using ssh does not imply that the parent process of the shell is  sshd. I noticed that when my approach stopped working at some point, namely:

So using  su to change to a different user or even working on screen will break this method.

Second approach: use who

who is a little program which shows who's logged in. I noticed that who behaves differently when issued locally and remotely. For example when I'm logged in locally I get:

But for remote logins:

It appears it is not necessary to extract the hostname information from this output, since who has a very useful option, which I think is a bit misdocumented, namely -m. The manpage for who claims that it outputs only hostname and user associated with stdin, whereas what it does is it filters out all login information for non-remote logins, if that sounds sensible.

Anyway, what I observed is that who -m will output a line for remote logins and nothing for local logins, and so far it's worked very well, whether I was using su or screen or not. This simplified my test to something like this:

Modifying the bash prompt

Now I could use the variable PS1 to make sure I know how I'm logged in at any time. I just added the following line to /etc/bash/bashrc (alternatively you can do this for just one user, by modifying ~/.bashrc):

And that's it.

One thought on “Logged in through ssh?”

Leave a Reply to windows vista games Cancel reply

Your email address will not be published. Required fields are marked *