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"

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

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

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

See also  Solved! Installing mysql gem - extconf.rb failed error

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

Leave a Comment