1. Technology
Send to a Friend via Email
You can opt-out at any time. Please refer to our privacy policy for contact information.

Net::SSH--The SSH (Secure Shell) Protocol

Automation with Net::SSH

By

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.

 ruby -ropenssl -e 'puts OpenSSL::OPENSSL_VERSION'
 

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.

 gem install net-ssh 

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.

 #!/usr/bin/env ruby
 require 'rubygems'
 require 'net/ssh'
 
 HOST = '192.168.1.113'
 USER = 'username'
 PASS = 'password'
 
 Net::SSH.start( HOST, USER, :password => PASS ) do|ssh|
 result = ssh.exec!('ls')
 puts result
 end
 

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.

See More About
  1. About.com
  2. Technology
  3. Ruby
  4. Networking
  5. SSH
  6. Automation with Net::SSH (Secure Shell)

©2014 About.com. All rights reserved.