How to SSH to a server using Ruby – Part I

ruby on rails

Welcome to Part I of how to SSH to a Linux, Windows, etc. server using Ruby. This post will give you a complete code example to get you up and running right away! The code below will connect to the server specific and run the ls -al command. Be sure to change the values in the example of @hostname, @username, @password, and @cmd to your own values.

Ruby Syntax

require 'rubygems'
require 'net/ssh'

@hostname = "localhost"
@username = "root"
@password = "password"
@cmd = "ls -al"

 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

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

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

See also  How to install Ruby 1.8.7 on CentOS 5.5 Linux

Support us & keep this site free of annoying ads.
Shop Amazon.com or Donate with Paypal

2 thoughts on “How to SSH to a server using Ruby – Part I”

Leave a Comment