Module: Net::SSH
- Defined in:
- lib/net/ssh.rb,
lib/net/ssh/test.rb,
lib/net/ssh/buffer.rb,
lib/net/ssh/config.rb,
lib/net/ssh/errors.rb,
lib/net/ssh/packet.rb,
lib/net/ssh/prompt.rb,
lib/net/ssh/version.rb,
lib/net/ssh/loggable.rb,
lib/net/ssh/test/kex.rb,
lib/net/ssh/multiplex.rb,
lib/net/ssh/proxy/http.rb,
lib/net/ssh/proxy/jump.rb,
lib/net/ssh/buffered_io.rb,
lib/net/ssh/key_factory.rb,
lib/net/ssh/known_hosts.rb,
lib/net/ssh/proxy/https.rb,
lib/net/ssh/test/packet.rb,
lib/net/ssh/test/script.rb,
lib/net/ssh/test/socket.rb,
lib/net/ssh/proxy/errors.rb,
lib/net/ssh/proxy/socks4.rb,
lib/net/ssh/proxy/socks5.rb,
lib/net/ssh/test/channel.rb,
lib/net/ssh/proxy/command.rb,
lib/net/ssh/connection/term.rb,
lib/net/ssh/service/forward.rb,
lib/net/ssh/test/extensions.rb,
lib/net/ssh/transport/state.rb,
lib/net/ssh/verifiers/never.rb,
lib/net/ssh/multiplex/client.rb,
lib/net/ssh/verifiers/always.rb,
lib/net/ssh/test/local_packet.rb,
lib/net/ssh/transport/session.rb,
lib/net/ssh/connection/channel.rb,
lib/net/ssh/connection/session.rb,
lib/net/ssh/test/remote_packet.rb,
lib/net/ssh/transport/constants.rb,
lib/net/ssh/authentication/agent.rb,
lib/net/ssh/connection/constants.rb,
lib/net/ssh/connection/keepalive.rb,
lib/net/ssh/transport/algorithms.rb,
lib/net/ssh/transport/gcm_cipher.rb,
lib/net/ssh/verifiers/accept_new.rb,
lib/net/ssh/connection/event_loop.rb,
lib/net/ssh/authentication/ed25519.rb,
lib/net/ssh/authentication/pageant.rb,
lib/net/ssh/authentication/session.rb,
lib/net/ssh/multiplex/control_path.rb,
lib/net/ssh/transport/kex/abstract.rb,
lib/net/ssh/transport/key_expander.rb,
lib/net/ssh/transport/hmac/abstract.rb,
lib/net/ssh/transport/packet_stream.rb,
lib/net/ssh/authentication/constants.rb,
lib/net/ssh/transport/cipher_factory.rb,
lib/net/ssh/transport/server_version.rb,
lib/net/ssh/multiplex/proxy_transport.rb,
lib/net/ssh/transport/identity_cipher.rb,
lib/net/ssh/authentication/certificate.rb,
lib/net/ssh/authentication/key_manager.rb,
lib/net/ssh/transport/kex/abstract5656.rb,
lib/net/ssh/authentication/methods/none.rb,
lib/net/ssh/authentication/security_key.rb,
lib/net/ssh/authentication/ed25519_loader.rb,
lib/net/ssh/authentication/methods/abstract.rb,
lib/net/ssh/authentication/methods/password.rb,
lib/net/ssh/transport/kex/curve25519_sha256.rb,
lib/net/ssh/authentication/methods/hostbased.rb,
lib/net/ssh/authentication/methods/publickey.rb,
lib/net/ssh/transport/kex/ecdh_sha2_nistp256.rb,
lib/net/ssh/transport/kex/ecdh_sha2_nistp384.rb,
lib/net/ssh/transport/kex/ecdh_sha2_nistp521.rb,
lib/net/ssh/authentication/pub_key_fingerprint.rb,
lib/net/ssh/transport/chacha20_poly1305_cipher.rb,
lib/net/ssh/verifiers/accept_new_or_local_tunnel.rb,
lib/net/ssh/transport/kex/curve25519_sha256_loader.rb,
lib/net/ssh/transport/kex/diffie_hellman_group1_sha1.rb,
lib/net/ssh/transport/chacha20_poly1305_cipher_loader.rb,
lib/net/ssh/transport/kex/diffie_hellman_group14_sha1.rb,
lib/net/ssh/authentication/methods/keyboard_interactive.rb
Overview
Net::SSH is a library for interacting, programmatically, with remote processes via the SSH2 protocol. Sessions are always initiated via Net::SSH.start. From there, a program interacts with the new SSH session via the convenience methods on Net::SSH::Connection::Session, by opening and interacting with new channels (Net::SSH::Connection:Session#open_channel and Net::SSH::Connection::Channel), or by forwarding local and/or remote ports through the connection (Net::SSH::Service::Forward).
The SSH protocol is very event-oriented. Requests are sent from the client to the server, and are answered asynchronously. This gives great flexibility (since clients can have multiple requests pending at a time), but it also adds complexity. Net::SSH tries to manage this complexity by providing some simpler methods of synchronous communication (see Net::SSH::Connection::Session#exec!).
In general, though, and if you want to do anything more complicated than simply executing commands and capturing their output, you'll need to use channels (Net::SSH::Connection::Channel) to build state machines that are executed while the event loop runs (Net::SSH::Connection::Session#loop).
Net::SSH::Connection::Session and Net::SSH::Connection::Channel have more information about this technique.
"Um, all I want to do is X, just show me how!"
X == "execute a command and capture the output"
Net::SSH.start("host", "user", password: "password") do |ssh|
result = ssh.exec!("ls -l")
puts result
end
X == "forward connections on a local port to a remote host"
Net::SSH.start("host", "user", password: "password") do |ssh|
ssh.forward.local(1234, "www.google.com", 80)
ssh.loop { true }
end
X == "forward connections on a remote port to the local host"
Net::SSH.start("host", "user", password: "password") do |ssh|
ssh.forward.remote(80, "www.google.com", 1234)
ssh.loop { true }
end
Defined Under Namespace
Modules: Authentication, BufferedIo, Connection, ForwardedBufferedIo, HostKeyEntries, Loggable, Multiplex, Proxy, Service, Test, Transport, Verifiers Classes: AuthenticationFailed, Buffer, ChannelOpenFailed, ChannelRequestFailed, Config, ConnectionTimeout, Disconnect, Exception, HostKeyError, HostKeyMismatch, HostKeyRevoked, HostKeyUnknown, HostKeys, KeyFactory, KnownHosts, NotSupportedOverControlMaster, Packet, Prompt, Timeout, UnsupportedKeyType, Version
Constant Summary collapse
- VALID_OPTIONS =
This is the set of options that Net::SSH.start recognizes. See Net::SSH.start for a description of each option.
i[ auth_methods bind_address compression compression_level config encryption forward_agent hmac host_key identity_agent remote_user keepalive keepalive_interval keepalive_maxcount kex keys key_data keycerts keycert_data languages logger password port proxy rekey_blocks_limit rekey_limit rekey_packet_limit timeout verbose known_hosts global_known_hosts_file user_known_hosts_file host_key_alias host_name user properties passphrase keys_only max_pkt_size max_win_size send_env set_env use_agent number_of_password_prompts append_all_supported_algorithms non_interactive password_prompt prompt_without_tty agent_socket_factory minimum_dh_bits verify_host_key fingerprint_hash check_host_ip pubkey_algorithms no_delay control_master control_path preopen_channels ]
Class Attribute Summary collapse
-
.default_configuration ⇒ Object
A callable that supplies default options for every connection made with Net::SSH.start, including those opened by libraries such as net-sftp, net-scp or SSHKit.
Class Method Summary collapse
- .assign_defaults(options) ⇒ Object
-
.configuration_for(host, use_ssh_config, user: nil) ⇒ Object
Returns a hash of the configuration options for the given host, as read from the SSH configuration file(s).
-
.start(host, user = nil, options = {}, &block) ⇒ Object
The standard means of starting a new SSH connection.
Class Attribute Details
.default_configuration ⇒ Object
A callable that supplies default options for every connection made
with Net::SSH.start, including those opened by libraries such as
net-sftp, net-scp or SSHKit. It is called with the host as passed to
start and the options read from ssh_config for it, and returns a Hash
of options. Set it to nil to remove it.
Options are applied in this order, later ones winning: ssh_config, the
hook's Hash, then the options passed to start. An option passed to
start as nil counts as not given, so the hook's value applies. The
hook can't set :user or :config, as both are needed to read ssh_config.
Net::SSH.default_configuration = ->(host, ssh_config) {
{ timeout: ssh_config.fetch(:timeout, 5), keepalive: true }
}
Net::SSH.start("host", "user") do |ssh|
# will have a default 5 seconds connection timeout
# will use keepalive
end
96 97 98 |
# File 'lib/net/ssh.rb', line 96 def default_configuration @default_configuration end |
Class Method Details
.assign_defaults(options) ⇒ Object
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 |
# File 'lib/net/ssh.rb', line 414 def self.assign_defaults() if ![:logger] [:logger] = Logger.new(STDERR) [:logger].level = Logger::FATAL end unless [:password_prompt] || [:prompt_without_tty] || Prompt.can_ask? [:non_interactive] = true end [:password_prompt] ||= Prompt.default() i[password passphrase].each do |key| .delete(key) if .key?(key) && [key].nil? end end |
.configuration_for(host, use_ssh_config, user: nil) ⇒ Object
Returns a hash of the configuration options for the given host, as read
from the SSH configuration file(s). If use_ssh_config is true (the
default), this will load configuration from both ~/.ssh/config and
/etc/ssh_config. If use_ssh_config is nil or false, nothing will be
loaded (and an empty hash returned). Otherwise, use_ssh_config may
be a file name (or array of file names) of SSH configuration file(s)
to read.
user is the explicitly requested remote user, matched by Match User.
See Net::SSH::Config for the full description of all supported options.
404 405 406 407 408 409 410 411 412 |
# File 'lib/net/ssh.rb', line 404 def self.configuration_for(host, use_ssh_config, user: nil) files = case use_ssh_config when true then Net::SSH::Config. when false, nil then return {} else Array(use_ssh_config) end Net::SSH::Config.for(host, files, user: user) end |
.start(host, user = nil, options = {}, &block) ⇒ Object
The standard means of starting a new SSH connection. When used with a block, the connection will be closed when the block terminates, otherwise the connection will just be returned. The yielded (or returned) value will be an instance of Net::SSH::Connection::Session (q.v.). (See also Net::SSH::Connection::Channel and Net::SSH::Service::Forward.)
Net::SSH.start("host", "user") do |ssh|
ssh.exec! "cp /some/file /another/location"
hostname = ssh.exec!("hostname")
ssh.open_channel do |ch|
ch.exec "sudo -p 'sudo password: ' ls" do |ch, success|
abort "could not execute sudo ls" unless success
ch.on_data do |ch, data|
print data
if data =~ /sudo password: /
ch.send_data("password\n")
end
end
end
end
ssh.loop
end
This method accepts the following options (all are optional). Omit an
option to use its default or ssh_config value; passing nil (or an array
containing nil) raises ArgumentError, except for :password,
:passphrase, :logger and :password_prompt, where nil means the default.
Options given here override Net::SSH.default_configuration, which
overrides ssh_config.
-
:auth_methods => an array of authentication methods to try
-
:bind_address => the IP address on the connecting machine to use in establishing connection. (:bind_address is discarded if :proxy is set.)
-
:check_host_ip => Also check IP address when connecting to remote host. Defaults to
true. -
:compression => the compression algorithm to use, or
trueto use whatever is supported. -
:compression_level => the compression level to use when sending data
-
:control_master => set to
:autoto run the session through an already running OpenSSH ControlMaster for the same host, port and user (started e.g. with ssh -M or ControlMaster auto), using its proxy mode (OpenSSH 7.4 or later). This skips the TCP connection, key exchange and authentication. If there is no usable master (no ControlPath, no socket, refused, timed out, owned by another user) Net::SSH logs why and connects as usual; it never starts a master itself. The master's own settings then apply instead of the options for setting up a connection (:keys, :key_data, :password, :passphrase, :auth_methods, :verify_host_key, :known_hosts, :host_key, :kex, :encryption, :hmac, :compression, :rekey_*, :proxy, :keepalive and the like); explicitly passed ones are named at info level. Over the master, remote port forwarding (Service::Forward#remote and #cancel_remote) raises Net::SSH::NotSupportedOverControlMaster, as the master consumes the global request reply, so success, failure and the port allocated for port 0 can't be observed; other global requests raise it too. Agent and X11 forwarding requests raise it too, and :forward_agent is ignored (logged at info level), because the master serves them from its own agent or display only if it has ForwardAgent or ForwardX11 enabled itself, and rejects them otherwise. Keepalive and rekeying are left to the master. ssh_config's ControlMaster is ignored, only this option enables it. An invalid ControlPath raises ArgumentError. A missing or stale socket is logged at info level, a socket that can't be used (another owner, refused, wrong protocol, timed out) at warn level. Has no effect on Windows. Defaults tofalse. -
:control_path => the ControlMaster socket to use with :control_master, with the same ~, $ENV and % tokens as ssh_config's ControlPath (%C, %d, %h, %i, %j, %k, %L, %l, %n, %p, %r, %u, %%). The master at that path decides which host and user the session is connected to, so a fixed path without %h, %p, %r or %C sends every host through the same master and the explicitly passed host key and authentication options are ignored. Defaults to ControlPath from ssh_config;
"none"disables the master. -
:config => set to
trueto load the default OpenSSH config files (~/.ssh/config, /etc/ssh_config), or tofalseto not load them, or to a file-name (or array of file-names) to load those specific configuration files. Defaults totrue. -
:encryption => the encryption cipher (or ciphers) to use
-
:forward_agent => set to true if you want the SSH agent connection to be forwarded. Ignored for a session through a ControlMaster (see :control_master).
-
:known_hosts => a custom object holding known hosts records. It must implement #search_for and
addin a similiar manner as KnownHosts. -
:global_known_hosts_file => the location of the global known hosts file. Set to an array if you want to specify multiple global known hosts files. Defaults to %w(/etc/ssh/ssh_known_hosts /etc/ssh/ssh_known_hosts2).
-
:hmac => the hmac algorithm (or algorithms) to use
-
:host_key => the host key algorithm (or algorithms) to use
-
:host_key_alias => the host name to use when looking up or adding a host to a known_hosts dictionary file
-
:host_name => the real host name or IP to log into. This is used instead of the
hostparameter, and is primarily only useful when specified in an SSH configuration file. It lets you specify an "alias", similarly to adding an entry in /etc/hosts but without needing to modify /etc/hosts. -
:keepalive => set to
trueto send a keepalive packet to the SSH server when there's no traffic between the SSH server and Net::SSH client for the keepalive_interval seconds. Defaults tofalse. -
:keepalive_interval => the interval seconds for keepalive. Defaults to
300seconds. -
:keepalive_maxcount => the maximun number of keepalive packet miss allowed. Defaults to 3
-
:kex => the key exchange algorithm (or algorithms) to use. Like KexAlgorithms, entries starting with +, - or ^ modify the default list. diffie-hellman-group14-sha1 is supported but not offered unless listed here (e.g. '+diffie-hellman-group14-sha1') or :append_all_supported_algorithms is set.
-
:keys => an array of file names of private keys to use for publickey and hostbased authentication
-
:keycerts => an array of file names of key certificates to use with publickey authentication
-
:keycert_data => an array of strings, which each element of the array being a key certificate to use with publickey authentication
-
:key_data => an array of strings, with each element of the array being a raw private key in PEM format.
-
:keys_only => set to
trueto use only private keys fromkeysandkey_dataparameters, even if ssh-agent offers more identities. This option is intended for situations where ssh-agent offers many different identites. -
:logger => the logger instance to use when logging
-
:max_pkt_size => maximum size we tell the other side that is supported per packet. Default is 0x8000 (32768 bytes). Increase to 0x10000 (65536 bytes) for better performance if your SSH server supports it (most do).
-
:max_win_size => maximum size we tell the other side that is supported for the window, i.e. how much the server may send on a channel before net-ssh reads it. Default is 0x200000 (2 MB), as in OpenSSH. Smaller values limit how much data is in flight; some servers (e.g. Mikrotik) truncate output when the window is small.
-
:minimum_dh_bits => the smallest group, in bits, accepted from the server in diffie-hellman-group-exchange key exchange. Defaults to 2048, as in OpenSSH; lower it (e.g. to 1024) only to reach legacy servers that offer nothing larger.
-
:no_delay => turns Nagle's algorithm off on the connection's socket (TCP_NODELAY), so a packet written while the previous one is still unacknowledged is sent right away instead of waiting for the server's ACK. OpenSSH does the same for every connection. Set to
falseto keep Nagle's algorithm on. Has no effect when the socket comes from a ProxyCommand, whose command owns the TCP connection. Defaults totrue. -
:non_interactive => set to true if your app is non interactive and prefers authentication failure vs password prompt. Non-interactive applications should set it to true to prefer failing a password/etc auth methods vs. asking for password. Like OpenSSH, Net::SSH never prompts when $stdin is not a TTY (e.g. in a background job), so it defaults to
truethen, unless :password_prompt or :prompt_without_tty is given or an SSH_ASKPASS program can be used (see Net::SSH::Prompt.askpass). -
:passphrase => the passphrase to use when loading a private key (default is
nil, for no passphrase) -
:password => the password to use to login
-
:port => the port to use when connecting to the remote host
-
:preopen_channels => set to
trueto keep one spare "session" channel open, so that Net::SSH::Connection::Session#open_channel can hand it out at once and a command that waits for the previous one to finish costs one round trip instead of two. The spare counts against the server's MaxSessions; if the server refuses it, pre-opening stops for the session. Defaults tofalse. -
:prompt_without_tty => set to
trueto prompt for passwords, key passphrases and keyboard-interactive responses on $stdout/$stdin even when $stdin is not a TTY, e.g. to read a password piped into the process. Defaults tofalse. -
:properties => a hash of key/value pairs to add to the new connection's properties (see Net::SSH::Connection::Session#properties)
-
:proxy => a proxy instance (see Proxy) to use when connecting
-
:pubkey_algorithms => the public key authentication algorithms to offer, in order of preference (e.g. %w[ssh-ed25519 rsa-sha2-512 rsa-sha2-256]). Keys whose type isn't listed are skipped. Like PubkeyAcceptedAlgorithms, entries starting with +, - or ^ modify the default list. ssh-rsa (SHA-1), [email protected] and ssh-dss are supported but not offered unless listed here (e.g. '+ssh-rsa') or :append_all_supported_algorithms is set.
-
:rekey_blocks_limit => the max number of blocks to process before rekeying
-
:rekey_limit => the max number of bytes to process before rekeying
-
:rekey_packet_limit => the max number of packets to process before rekeying
-
:send_env => an array of local environment variable names to export to the remote environment. Names may be given as String or Regexp.
-
:set_env => a hash of environment variable names and values to set to the remote environment. Override the ones if specified in
send_env. -
:timeout => how long to wait for the initial connection to be made
-
:user => the user name to log in as; this overrides the
userparameter, and is primarily only useful when provided via an SSH configuration file. -
:remote_user => used for substitution into the '%r' part of a ProxyCommand; defaults to the user name the connection logs in as.
-
:user_known_hosts_file => the location of the user known hosts file. Set to an array to specify multiple user known hosts files. Defaults to %w(~/.ssh/known_hosts ~/.ssh/known_hosts2).
-
:use_agent => Set false to disable the use of ssh-agent. Defaults to true
-
:identity_agent => the path to the ssh-agent's UNIX socket
-
:verbose => how verbose to be (Logger verbosity constants, Logger::DEBUG is very verbose, Logger::FATAL is all but silent). Logger::FATAL is the default. The symbols :debug, :info, :warn, :error, and :fatal are also supported and are translated to the corresponding Logger constant.
-
:append_all_supported_algorithms => set to
trueto append all supported algorithms by net-ssh, except thenonecipher and MAC, which must be named explicitly (e.g. encryption: '+none'). Was the default behaviour until 2.10 -
:number_of_password_prompts => Number of prompts for the password authentication method defaults to 3 set to 0 to disable prompt for password auth method
-
:password_prompt => a custom prompt object with ask method. See Net::SSH::Prompt
-
:agent_socket_factory => enables the user to pass a lambda/block that will serve as the socket factory Net::SSH.start(host,user,agent_socket_factory: ->{ UNIXSocket.open('/foo/bar') }) example: ->{ UNIXSocket.open('/foo/bar')}
-
:verify_host_key => specify how strict host-key verification should be. In order of increasing strictness:
- :never (very insecure) ::Net::SSH::Verifiers::Never
- :accept_new_or_local_tunnel (insecure) ::Net::SSH::Verifiers::AcceptNewOrLocalTunnel
- :accept_new (insecure) ::Net::SSH::Verifiers::AcceptNew
- :always (secure) ::Net::SSH::Verifiers::Always
You can also provide an own Object which responds to
verifyandverify_signature. The argument given toverifyis a hash consisting of the:key, the:key_blob, the:fingerprintand the:session. Returning true accepts the host key, returning false declines it and closes the connection.verify_signatureis given a block that checks the server's host key signature and must return the block's result.
-
:fingerprint_hash => 'MD5' or 'SHA256', defaults to 'SHA256' If
userparameter is nil it defaults to USER from ssh_config, or local username
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 |
# File 'lib/net/ssh.rb', line 329 def self.start(host, user = nil, = {}, &block) () Multiplex.() = .keys host_arg = host = configuration_for(host, .fetch(:config, true), user: user || [:user]) = (host, ) = .merge(, .compact) assign_defaults() [:user] = user if user host = .fetch(:host_name, host) [:check_host_ip] = true unless .key?(:check_host_ip) if [:non_interactive] [:number_of_password_prompts] = 0 end if [:verbose] [:logger].level = case [:verbose] when Integer then [:verbose] when :debug then Logger::DEBUG when :info then Logger::INFO when :warn then Logger::WARN when :error then Logger::ERROR when :fatal then Logger::FATAL else raise ArgumentError, "can't convert #{options[:verbose].inspect} to any of the Logger level constants" end end user = .fetch(:user, user) || Etc.getpwuid.name [:remote_user] ||= user connection = Multiplex.connect(host_arg, host, user, , explicit: ) if [:control_master] connection ||= connect_directly(host, user, ) if block_given? begin yield connection ensure connection.close unless connection.closed? end else connection end end |