Ruby Net::SSH, The SSH (Secure Shell) Protocol

Automation with Net::SSH

man working at computer
PeopleImages/DigitalVision/Getty Images

SSH (or "Secure Shell") is a network protocol that allows you to exchange data with a remote host over an encrypted channel. It's most commonly used as an interactive shell with Linux and other UNIX-like systems. You may use it to log into a Web server and run a few commands to maintain your website. It can also do other things, though, such as transfer files and forward network connections.

Net::SSH is a way for Ruby to interact with SSH. Using this gem, you can connect to remote hosts, run commands, examine their output, transfer files, forward network connections, and do anything you would normally do with an SSH client. This is a powerful tool to have if you frequently interact with remote Linux or UNIX-like systems.

Installing Net::SSH

The Net::SSH library itself is pure Ruby--it requires no other gems and doesn't need a compiler to install. However, it does rely on the OpenSSL library to do all the encryption needed. To see if OpenSSL is installed, run the following command.

If the Ruby command above outputs an OpenSSL version, it's installed and everything should work. The Windows One-Click Installer for Ruby includes OpenSSL, as do many other Ruby distributions.

To install the Net::SSH library itself, install the net-ssh gem.

Basic Usage

The most common way to use Net::SSH is to use the Net::SSH.start method. This method takes the hostname, username and password and will either return an object representing the session or pass it to a block if given one. If you give the ​start method a block, the connection will be closed at the end of the block. Otherwise, you'll have to manually close the connection when you're finished with it.

The following example logs into a remote host and gets the output of the ls (list files) command.

Within the block above, the ssh object refers to the open and authenticated connection. With this object, you can launch any number of commands, launch commands in parallel, transfer files, etc. You might also notice that the password was passed as a hash argument. This is because SSH allows for a variety of authentication schemes, and you need to tell it this is a password.

mla apa chicago
Your Citation
Morin, Michael. "Ruby Net::SSH, The SSH (Secure Shell) Protocol." ThoughtCo, Aug. 27, 2020, Morin, Michael. (2020, August 27). Ruby Net::SSH, The SSH (Secure Shell) Protocol. Retrieved from Morin, Michael. "Ruby Net::SSH, The SSH (Secure Shell) Protocol." ThoughtCo. (accessed May 29, 2023).