How to keep logs of ssh sessions

root's picture

Ever wonder how to log ssh sessions? Well, there are many possibilities but what I will show you here is probably the simplest way and most important: tested.

1. Create the directory where you want to put the logs:
(I choose to make it readable only by my username)

florian@mobilebox:~$ mkdir -p /home/florian/logs/ssh/
florian@mobilebox:~$ chmod 700 /home/florian/logs/ssh/
florian@mobilebox:~$ ls -lad /home/florian/logs/ssh/
drwx------ 2 florian florian 359176 2012-02-17 08:36 /home/florian/logs/ssh/

2. Create the magic line (you cannot call it script :) and make it executable:

florian@mobilebox:~$ echo 'script -f -a -q -c "/usr/bin/ssh $*" /home/florian/logs/ssh/$(date +%Y-%m-%d-%H-%M-%S)_$1.log' >/home/florian/bin/sshlog
florian@mobilebox:~$ cat /home/florian/bin/sshlog
script -f -a -q -c "/usr/bin/ssh $*" /home/florian/logs/ssh/$(date +%Y-%m-%d-%H-%M-%S)_$1.log
florian@mobilebox:~$ chmod +x /home/florian/bin/sshlog
florian@mobilebox:~$ ls -la /home/florian/bin/sshlog
-rwxr-xr-x 1 florian florian 104 2012-02-16 12:57 /home/florian/bin/sshlog

3. Add in ~/.bashrc the following line and then logout/login to your user:

florian@mobilebox:~$ echo "alias ssh='/home/florian/bin/sshlog'" >> ~/.bashrc
florian@mobilebox:~$ grep ssh ~/.bashrc
alias ssh='/home/florian/bin/sshlog'

4. Verify the alias:

florian@mobilebox:~$ type ssh
ssh is aliased to `/home/florian/bin/sshlog'

5. Now use ssh as normal and see the results:

florian@mobilebox:~$ ls -lrt /home/florian/logs/ssh/* | tail
-rw-r--r-- 1 florian florian    916022 2012-02-16 11:20 /home/florian/logs/ssh/2012-02-14-09-41-41_core.log

Thou shalt not steal!

If you want to use this information on your own website, please remember: by doing copy/paste entirely it is always stealing and you should be ashamed of yourself! Have at least the decency to create your own text and comments and run the commands on your own servers and provide your output, not what I did!

Or at least link back to this website.

Recent content