How to SSH to a server using Ruby – Part II

ruby on rails

Welcome to Part II of how to SSH to a server using Ruby.  In Part I of this article, we gave you a simple example of how to SSH to a server and run a command. The hostname, username, password, and the command to execute were hardcoded in the example.

In this article, we will expand on the first example by allowing you to specify the server connection information and the command to execute as command-line parameters.  This will allow you to use the same script to connect to a variety of servers and execute any command without modifying the script over and over.

Ruby Syntax

require 'rubygems'
require 'net/ssh'
require 'optparse'

opts = OptionParser.new
opts.on("-h HOSTNAME", "--hostname NAME", String, "Hostname of Server") { |v| @hostname = v }
opts.on("-u SSH USERNAME", "--username SSH USERNAME", String, "SSH Username of Server") { |v| @username = v }
opts.on("-p SSH PASSWORD", "--password SSH PASSWORD", String, "SSH Password of Server") { |v| @password = v }
opts.on("-c SHELL_COMMAND", "--command SHELL_COMMAND", String, "Shell Command to Execute") { |v| @cmd = v }
begin
  opts.parse!(ARGV)
rescue OptionParser::ParseError => e
  puts e
end
raise OptionParser::MissingArgument, "Hostname [-h]" if @hostname.nil?
raise OptionParser::MissingArgument, "SSH Username [-u]" if @username.nil?
raise OptionParser::MissingArgument, "SSH Password [-p]" if @password.nil?
raise OptionParser::MissingArgument, "Command to Execute [-c]" if @cmd.nil?

 begin
    ssh = Net::SSH.start(@hostname, @username, :password => @password)
    res = ssh.exec!(@cmd)
    ssh.close
    puts res
  rescue
    puts "Unable to connect to #{@hostname} using #{@username}/#{@password}"
  end

Example of how to execute the script

ruby script_name.rb -h localhost -u root -p password -c "ls -al"

As you can see, the hostname, username, password, and command are all parameters passed in to the script. All of these parameters are required, so if you forget one, it will spit out an error. Give it a try!

See also  How to install Ruby 1.8.7 on CentOS 5.5 Linux

Part I – How to SSH using Ruby, a simple example

Part II – How to SSH using Ruby, with command-line arguments

Leave a Comment