Log Out SSH User in Bash

So, I've been writing a system to allow users temporary access onto a system.

Essentially, there's a web server with a PHP script, the PHP script takes a Username & Password from a webform, and passes it to a script, createusr.sh.

The script looks something like this:

pass=$(perl -e 'print crypt($ARGV[0], "password")' $2)
sudo /usr/sbin/useradd $1 -s /bin/bash -p $pass -d /home/onlineusers/$1 -m
sudo /bin/chmod 700 /home/onlineusers/$1
sleep 1800
sudo /usr/sbin/userdel -f $1
sudo /bin/rm -rf /home/onlineusers/$1

Basically it creates a user, using the passed parameters, and force creates their home directory. It then makes that directory only accessible to said user, before sleeping for half an hour.

After that time it deletes the user and their home directory. But I have one problem. If the user is still logged on at that point, then the user deletion has no effect, as the user can still work.

At the moment, I am thinking of using:

pgrep -t <user's tty>

and then killing the bash, but I'm not sure how I can get the TTY of a user logged in through SSH?

Maybe somehow "grep" with "w" might do it, but not if the username contains something like "load" which is featured elsewhere in the output from "w".

Besides this, is there any way that I can send a message to a logged in user, saying something like "5 minutes left"?

write

seems like a possibility, but I'm not sure exactly how this would be implemented.

Not sure I understand the problem in it's entirety. Try

USERTTY=$(who | awk '$0 ~ user {print $2}' user=$1)
write $1 $USERTTY

Thankyou so much! Helped loads!

I ended up with:

pass=$(perl -e 'print crypt($ARGV[0], "password")' $2)
sudo /usr/sbin/useradd $1 -s /bin/bash -p $pass -d /home/onlineusers/$1 -m -g onlineusers
sudo /bin/chmod 700 /home/onlineusers/$1
echo -e "\n"
sleep 1800
USERTTY=$(who | awk '$0 ~ user {print $2}' user=$1)
BASHPROC=$(pgrep -t $USERTTY | sed -n 1p)
kill -HUP $BASHPROC
sudo /usr/sbin/userdel -f $1
sudo /bin/rm -rf /home/onlineusers/$1