-
-
Save kivanio/50eb02386e0828e46afa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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