Quick Start Guide
This guide provides a minimal, step-by-step example of how to connect to a remote server with Net::SSH and execute a simple command.
Connecting and Executing a Command
The primary entry point for Net::SSH is the Net::SSH.start
method. It handles the connection, authentication, and session setup. The easiest way to use it is with a block, which ensures the connection is automatically closed when you're done.
Here's a complete script that connects to a server and prints its hostname.
require 'net/ssh'
# --- Configuration ---
host = 'your_server_hostname_or_ip'
user = 'your_username'
password = 'your_password'
begin
# --- Establish the connection ---
Net::SSH.start(host, user, password: password) do |ssh|
# --- Execute a command ---
# The exec! method blocks until the command finishes.
command = 'hostname'
output = ssh.exec!(command)
# --- Print the output ---
puts "Executing '#{command}' on #{host}..."
puts output
end
rescue Net::SSH::AuthenticationFailed
puts "Authentication failed for user '#{user}'."
rescue => e
puts "An error occurred: #{e.message}"
puts e.backtrace
end
How it Works
-
require 'net/ssh'
: This line loads the Net::SSH library. -
Net::SSH.start(host, user, password: password)
: This is the core of the library.- The first two arguments are the hostname and username.
- Options are passed as a hash. Here, we use
:password
for password-based authentication. - When given a block,
start
yields aNet::SSH::Connection::Session
object (here,ssh
). - The connection is automatically closed when the block exits.
-
ssh.exec!(command)
: This method executes a command on the remote server synchronously.- It waits for the command to complete.
- It returns all standard output (
stdout
) generated by the command as a single string. - If the command writes to standard error (
stderr
), that output is discarded byexec!
. To capturestderr
, see the Usage Guide.
Running the Example
- Save the code above to a file (e.g.,
ssh_test.rb
). - Replace the placeholder values for
host
,user
, andpassword
with your actual server credentials. -
Run the script from your terminal:
ruby ssh_test.rb
You should see the hostname of your remote server printed to the console.
What's Next?
This example covers the most basic use case. For more advanced topics like asynchronous command execution, handling stdout
and stderr
streams separately, port forwarding, and using different authentication methods, check out the Usage Guide.