Detecting if another user is connected on UNIX systems

How to detect if another user is connected to your machine or your server? You can use the command “users” to check yourself is someone is connected. But to do it automatically, you’ll have to use some pipe :

[code lang=”bash”]expr length “`users | sed -e “s/\($USER\|\[ \]*\)//ig”`”[/code]

The first thing executed by the shell will be the thing under french apostrophe ( ` ). Theses are for evaluation a command, and replace it by what it outputs (normally print on the screen). The command users print the list of connected users into a pipe, to sed which evaluate its command as a regular expression (-e parameter). The command is “s” for substitute, and the rest tells him to find “$USER” (replaced by the currently connected user, you) and spaces and replace them by … nothing. So this part will be an empty string if there is no other users connected than “$USER” and something not empty if there is.

The “expr length” return the length of a string. So this commands print 0 if there is no other user connected, and >0 if there is some !

In a shell script to do something if yes or no…
[code lang=”bash”]#!/bin/sh
usersstripped=`users | sed -e “s/\(tom\|\[ \]*\)//ig”`
connected=`expr length “$usersstripped”`
if [ “$connected” -eq “0” ] ; then
echo “No other user is connected”
else
echo “Other user connected !”
fi[/code]

It is essentially the same command but done in two times, as in a shell script this command would not be evaluated correctly.

And if you want to put that in a cron to eg. send you a mail, you just have to type “crontab -e” and put a line like :

[code]* * * * * /home/tom/connected[/code]

To launch it every minutes. But if you do that you’d better do something like detecting a connection…