Sha256: 7c63eb4658bf6da80384833226deb866d571c278f78d24c72f2a762fd766eb50

Contents?: true

Size: 1.44 KB

Versions: 1

Compression:

Stored size: 1.44 KB

Contents

require 'net/ssh'
require 'timeout'

module Seeker
  class SSH
    TIMEOUT = 5
    PROMPT  = /^[^\s>#]+[>#] /
    SLEEP   = 0.001
    attr_reader :prompt_seen
    class NoSshShell < SeekerError; end

    def cmd command
      Log.debug "SSH: #{command}"
      @output = ''
      @session.send_data command + "\n"
      @session.process
      expect @prompt
      @output
    end

    def close command='exit'
      @session.send_data command +"\n"
    end

    private

    def initialize host, user, password, prompt=PROMPT
      @output      = ''
      @prompt      = prompt
      @prompt_seen = nil
      @session     = nil
      @ssh = Net::SSH.start host, user, :password=>password, :timeout=>TIMEOUT
      shell_open
      expect @prompt
    end

    def shell_open
      @session = @ssh.open_channel do |channel|
        channel.on_data do |channel, data|
          $stderr.print data  if Seeker.debug > 1
          @output << data
        end
        channel.request_pty do |channel, success|
          raise NoSshShell, "Can't get PTY" unless success
          channel.send_channel_request 'shell' do |channel, success|
            raise NoSshShell, "Can't get shell" unless success
          end
        end
      end
    end

    def expect regexp
      Timeout::timeout(TIMEOUT) do
        @ssh.loop(SLEEP) do
          sleep SLEEP
          re = @output.match regexp
          @prompt_seen = re[0] if re
          not re
        end
      end
    end


  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
seeker-junos-0.2.0 lib/seeker/ssh.rb