Skip to content

Instantly share code, notes, and snippets.

@jadon1979
Last active December 19, 2015 02:49
Show Gist options
  • Save jadon1979/5886133 to your computer and use it in GitHub Desktop.
Save jadon1979/5886133 to your computer and use it in GitHub Desktop.
ssh wrapper
class SshBase
attr_accessor :host, :username, :password, :timeout
class SSHException < Exception; end;
# Callbacks storage for Channel Execute Callbacks
class ChannelExecCallBacks
attr_accessor :on_success, :on_failure, :on_data, :on_extended_data, :on_close
end
def initialize
@timeout = 1200 # 20 minutes
end
# Initiate SSH Connection
def start(method_to_send)
init_ssh { |ssh| channel_open ssh, method_to_send }
end
# Open an SSH Channel
def channel_open(ssh, method_to_send)
ssh.open_channel { |channel| method_to_send(channel) }
end
# Execute SSH CMDs on an open Channel
def channel_exec(channel, cmd)
channel.exec(cmd) do |ch, success|
channel_exec_call_backs = ChannelExecCallBacks.new
yield channel_exec_call_backs
channel_exec_call_backs.tap do |call_back|
send call_back.on_success if success && !call_back.on_success.nil?
send call_back.on_failure unless success && call_back.on_failure.nil?
channel.on_data { |ch, data| send call_back.on_data, ch, data } unless call_back.on_data.nil?
channel.on_extended_data { |ch, data| send call_back.on_extended_data, ch, data } unless call_back.on_extended_data.nil?
channel.on_close { |ch, data| send call_back.on_close, ch, data } unless call_back.on_close.nil?
end
end
end
private
def init_ssh
begin
@ssh ||= ::Net::SSH.start("#{@host}", "#{@username}", { :password => "#{@password}", :timeout => @timeout }) do |ssh|
yield ssh
ssh.loop
end
rescue => e
raise new SSHException("SSH Exception: #{e.message}")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment