How to log SSH session output in Linux?

Introduction

In this article we will see how it is possible to log SSH or telnet session output to a file. I usually use this method for saving the configuration of remote network devices like routers or switches, but it might be useful in any other situations when you need to save all session output to a text file.

Tee Linux Command

Tee is a Linux utility which reads from standard input and writes to both standard output and a file. In other words, instead of sending something directly to standard output (your terminal) you can send stream to tee and it will forward your stream to standard output and send a copy to the file.

When you log into a remote device using SSH/telnet you get a stream which is sent to your standard output (terminal), so you can interact with the remote device. Now if you pipe that output to teeĀ it will still give you a copy of that stream (standard output) and at the same time write that output to the specified file.

Example

Now I will connect to my firewall and log the output:

orkhans@ubuntu1:~$ ssh admin@172.16.10.1 | tee log.txt
admin@172.16.10.1's password: 
fortigate300d # 
config      Configure object.
get         Get dynamic and system information.
show        Show configuration.
diagnose    Diagnose facility.
execute     Execute static commands.
exit        Exit the CLI.
 
fortigate300d # exit

The log.txt file contains the same output log:

orkhans@ubuntu1:~$ cat log.txt 
fortigate300d # 
config      Configure object.
get         Get dynamic and system information.
show        Show configuration.
diagnose    Diagnose facility.
execute     Execute static commands.
exit        Exit the CLI.
 
fortigate300d # exit

You can use -a option if you want to append the output to the file instead of overwriting it, which is the default behavior:

orkhans@ubuntu1:~$ ssh admin@172.16.10.1 | tee -a log.txt

Conclusion

Now you know how to use tee command for logging session output. Thank you for reading.

Tags:

Add a Comment