Monday, September 2, 2013

How to find what is the current working directory of a remotely logged ssh session to a Linux server and disconnect remote sessions

First you need to get the list of users currently connected to your server. You can use "last" command to achieve that. "last" command shows the list of users currently logged in or recently logged in to the system through various terminals. If the user still is connected to the system through the relevant terminal, you can see "still logged in" part in the output row related to that user.
If the user is connected remotely (for example, by ssh), you can see the his terminals related to remote sessions has the prefix "pts" (Pseudo Terminals) and in the third column of output, you can see the remote IP of the machine which the user connected from.

[root@10 ~]# last | grep "still logged"
root     pts/2        192.168.18.1     Mon Sep  2 21:42   still logged in   
root     pts/1        :0.0             Mon Sep  2 21:12   still logged in   
root     :0                            Mon Sep  2 21:11   still logged in 

Then you can find the processes originated by  the user by a connected pseudo terminal using "ps" command and grep command.

[root@10 ~]# ps -ef | grep -v grep | grep "pts/2"
root      6224  3971  0 21:42 ?        00:00:00 sshd: root@pts/2 
root      6229  6224  0 21:42 pts/2    00:00:00 -bash

In the above output, you can see the processes initiated by the remote connection. The first process "sshd" is the process used to initiate the remote connection to this machine. The next process is the shell the remote user has logged into. Therefore the process we needs to check is the second process which "-bash" shell process.

By killing "sshd: root@pts/2" or "-bash" process (process ID 6224 or 6229), you can disconnect this user from the server.

We can use one of following command to get the current working directory of the remotely connected user in "pts/2".

[root@10 ~]# pwdx 6229
6229: /product/softwares

Or

[root@10 ~]# readlink /proc/6229/cwd
/product/softwares

Or

[root@10 ~]# lsof -p 6229 
COMMAND  PID USER   FD   TYPE DEVICE     SIZE    NODE NAME
bash    6229 root  cwd    DIR  253,0     4096  397609 /product/softwares
bash    6229 root  rtd    DIR  253,0     4096       2 /



~~~


No comments: