Tag: history

  • Show IP address in history

    On the Linux Server, the history command shows previously executed commands. If you have many people working on a server, it is better log IP address of the user who run the command along with time for security reason.

    To log, IP and date, create a file

    vi /usr/local/bin/sok_detailed_history

    In the file, add

    #!/bin/bash
    # Author: ServerOK.in
    # Email: [email protected]
    # Web; https://serverok.in
    
    SET_IP=`echo -n $SSH_CLIENT|cut -d' ' -f1`
    if [[ `tail -n1 ~/.bash_history|rev|cut -c -4|rev` != `date +%Y` ]]
    then
        sed -i "\$s/$/ #entered by `echo -n $SET_IP` on `date`/g" ~/.bash_history
    fi

    Make it executable

    chmod 755 /usr/local/bin/sok_detailed_history

    Create file

    vi  /etc/profile.d/sok_detailed_history.sh

    Add the following to the file

    export PROMPT_COMMAND="history -a; /bin/bash /usr/local/bin/sok_detailed_history"

    Log out and log in to the server. Now your history will also record IP address that is used to login to server. PROMPT_COMMAND environment variable allows you to execute a command every time command promt is shown. To see how PROMPT_COMMAND works, just run

    PROMPT_COMMAND="echo I am here"

    Example

    boby@sok-01:~$ PROMPT_COMMAND="echo I am here"
    I am here
    boby@sok-01:~$ 
    I am here
    boby@sok-01:~$ 
    I am here
    boby@sok-01:~$ 

    Every time I press enter, the command specified in the PROMPT_COMMAND variable gets executed. Just close the current terminal to undo the change.

    See history

  • history

    To get history show time

    echo 'export HISTTIMEFORMAT="%d/%m/%y %T "' >> ~/.bashrc
    source  ~/.bashrc

    history -a will append your current session history to the content of the history file.

    history -w will replace the content of the history file with your current session history.

    To remove the line number from history, run

    history | sed 's|[0-9]\+\s\+||'

    Or

    history | cut -d' ' -f5-40

    Log everything

    To log everything, edit

    vi /etc/bash.bashrc

    Add

    test "$(ps -ocommand= -p $PPID | awk '{print $1}')" == 'script' || (script -f $HOME/$(date +"%d-%b-%y_%H-%M-%S")_shell.log)

    Or manually start logging in with

    script -f $HOME/session.log

    Linux Server show IP address in history

    Method 2: Log Commands

    edit /etc/profile

    vi /etc/profile

    At end of the file, add

    export HISTTIMEFORMAT="%F %T "
    PROMPT_COMMAND='echo "$(date +"%F %T") `whoami` from `who -u am i 2>/dev/null | awk "{print \$NF}" | tr -d "()"` ran `history 1 | sed "s/^[ ]*[0-9]\+[ ]*//"`" >> /var/log/commands.log'