Net::SSH: Pure Ruby SSH
Net::SSH is a pure-Ruby implementation of the SSH2 client protocol. It allows you to write programs that invoke and interact with processes on remote servers, via SSH2.
Key Features
- Execute Remote Processes: Run commands on remote servers and capture their standard output and standard error streams.
- Multiplexed Connections: Run multiple processes in parallel over a single SSH connection using channels.
- Port Forwarding: Forward local ports to a remote host, or remote ports to a local host.
- SSH Subsystem Support: Integrate with SSH subsystems like SFTP.
- Rich Authentication: Supports password, public key, keyboard-interactive, and SSH agent authentication.
- Proxy Support: Connect through various proxy types including HTTP, SOCKS4/5, and custom commands (
ProxyCommand
/ProxyJump
). - Configuration Compatibility: Reads and applies settings from standard OpenSSH configuration files (
~/.ssh/config
).
Synopsis
Here is a brief look at what you can do with Net::SSH:
require 'net/ssh'
Net::SSH.start('host', 'user', password: "password") do |ssh|
# Capture all stderr and stdout output from a remote process
output = ssh.exec!("hostname")
puts "Remote hostname: #{output}"
# Open a new channel and run a command asynchronously
channel = ssh.open_channel do |ch|
ch.exec("/usr/local/bin/ruby /path/to/file.rb") do |ch, success|
raise "could not execute command" unless success
# "on_data" is called when the process writes to stdout
ch.on_data do |c, data|
$stdout.print data
end
# "on_extended_data" is called when the process writes to stderr
ch.on_extended_data do |c, type, data|
$stderr.print data
end
ch.on_close { puts "done!" }
end
end
# Wait for the channel to finish
channel.wait
# Forward connections on local port 1234 to port 80 of www.example.org
ssh.forward.local(1234, "www.example.org", 80)
puts "Forwarding local port 1234. Press Ctrl-C to stop."
ssh.loop { true }
end
For a deeper dive, check out the Quick Start Guide and the Usage Guide.