To know which IP executed a certain command in linux using ssh

There is a server which is accessed by many users using ssh. I am trying to figure out which user executed a certain command.

I can know the list of users currently accessing server using who Also I will know the list of command executed using history.

But how to know which user executed a command like cp file1.sh file2.sh in the server? The user has already executed the command and logged out


Each new user connecting spawns a new sshd session with a specific PID. You could use pstree to print which commands are inherited from which sshd session, and then cross check this PID in /var/log/auth.log.

Example (anonymized): I logged in to a remote server with 3 simultaneous sessions, with the same remote user. I now want to find out from which IP the client came that ran the command watch date.

$ pstree -p | grep watch
        |           |-sshd(15243)---sshd(15342)---bash(15343)---watch(15450)
$ sudo grep 15243 /var/log/auth.log
Mar  7 15:37:29 XXXXXXXXXX sshd[15243]: Accepted publickey for XXXXXXXXXX from 12.34.56.78 port 48218 ssh2
Mar  7 15:37:29 XXXXXXXXXX sshd[15243]: pam_unix(sshd:session): session opened for user XXXXXXXXXX by (uid=0)
Mar  7 15:37:44 XXXXXXXXXX sudo: XXXXXXXXXX : TTY=pts/7 ; PWD=/home/XXXXXXXXXX ; USER=root ; COMMAND=/bin/grep 15243 /var/log/auth.log

pstree -p shows that the watch command is inherited from sshd with PID 15243. greping for this PID in /var/auth/auth.log shows that it was IP 12.34.56.78 that started this session. Therefore this is also the user that started watch.

As for finding history for specifically this user, it cannot be done from what I can see when all remote users are using the same local SSH user. Also, it can easily be spoofed/inactivated/etc., so it's not really reliable. If it is saved to the history file, then you could just look for the cp command and look backwards in the file, but if it is not there, then there is not much to do.


You can add this two lines to /etc/profile or /etc/bashrc in order to log all commands executed by bash:

whoami="$(whoami)@$(echo $SSH_CONNECTION | awk '{print $1}')"                                                                                                  
export PROMPT_COMMAND='RETRN_VAL=$?;logger -p local3.debug "$whoami [$$]: $(history 1 | sed "s/^[ ]*[0-9]\+[ ]*//" ) [$RETRN_VAL]"'

This will use syslog to record every executed command along with the user who did and it's IP address in a format like this:

Jan  8 08:43:49 xpto local3.debug root: [email protected] [29385]: ls -al [0]

Additionally you can add the line below to your syslog configuration ( /etc/syslog.conf ) to redirect the local3 messages to a specific file.

local3.*                                                /var/log/prompt.log