Time to note down some SSH tricks. Vim, Git, Unix, SSH! All very efficient when you spend some time learning the ins and outs.

Key-based login

It is hard to keep up with many hostnames and passwords so first thing to set up is a key-based login. First run ssh-keygen -t dsa and then ssh-copy-id (if not present check out this one-liner)

The power of ~/.ssh/config

Man. Check out this nice intro. Using this file is more convenient than shell aliases. I even used this file to solve a mysterious "Too many authentication failures for [user]" which happened (ssh -v) when multiple keys were offered to the remote host!

X11 forwarding

Run ssh -X host to show remote X applications on your local screen (if X is running on your local machine)

Run commands on a remote server

ssh user@remote_host 'cmd' - this is a powerful way to quickly analyze data on different hosts without the burden of logging in and copying terminal output. See a nice Perl loop example.

Pipe data from/to a remote system

One of my favorites: see this post for two powerful examples:

  • 1. send a big directory to a another server compressing / uncompressing it via the pipe-to-ssh:
  • $ tar -cz content | ssh user@remote_host 'tar -xz'

    The other way around works just as well to get files off a remote server: $ ssh remote_host tar c content/ | tar xv

  • 2. backup a remote mysql database to STDOUT and receive it via pipe/SSH as STDIN to import it into a local DB:
  • $ ssh user@remote_host 'mysqldump -udbuser -ppassword dbname' | mysql -uroot -ppassword backup

    Mount a remote directory

    $ sshfs user@remote_host:/home/user/documents local_folder/ - see this ssh hacks post.

    Practical example

    This just happened trying to convert this post from text to html:

    $ perl parsepost.pl 2013.05.12_ssh_tricks.txt 
    Can't locate HTML/Entities.pm in @INC ...

    Instead of fixing it right away I took the opportunity to try a quick workaround via ssh:

    # cat the txt post to STDOUT,
    # via pipe/ssh to remote server it goes into perl script as STDIN (-), 
    # the result is redirected to a file on my local server,
    # note that I can do "ssh bob" thanks to my .ssh/config setup ;)
    $ cat 2013.05.12_ssh_tricks.txt | ssh bob <path>/perl/wordpress_parse_post.pl - > 2013.05.12_ssh_tricks.html

    Only the beginning

    Forwarding, tunneling, proxies, access to services through a firewall ... much more is possible. Check out SSH: More than secure shell for other SSH use cases.

    Your favorite SSH trick/ hack?

    Feel free to comment below ...

Bob Belderbos

Software Developer, Pythonista, Data Geek, Student of Life. About me