Ruby Method to Run Shell Command Over SSH with Real-Time Console Output

From Bonus Bits
Jump to: navigation, search

Purpose

This article gives the steps to use Ruby Net SSH library to run a shell command on a host over SSH with real-time console output.


Prerequisites

  • Ruby 2.6.5+


Ruby Method

def ssh_command(host, user, ssh_key, command)
  require 'net/ssh'

  retries = 0
  code = nil
  Net::SSH.start(
    host, user,
    host_key: 'ssh-rsa',
    keys: [ssh_key],
    verify_host_key: false
  ) do |ssh|
    the_channel = ssh.open_channel do |channel|
      channel.exec command do |ch, success|
        raise 'could not execute command' unless success

        ch.on_data { |_c, data| print data }
        ch.on_extended_data { |_c, _type, data| print data }
        ch.on_request('exit-status') { |_ch, data| code = data.read_long }
      end
    end
    the_channel.wait
  end
  abort "#{command} returned #{code} !!" if code != 0
rescue Net::SSH::ConnectionTimeout
  puts 'Net::SSH::ConnectionTimeout'
  retry if (retries += 1) < 3
end


Usage Examples

ssh_command('10.10.10.100', 'ubuntu', '/home/ubuntu/.ssh/id_rsa', 'tail -f /var/log/cloud-init-output.log')


Related Articles