Class: Xssh::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/xssh/connection.rb

Defined Under Namespace

Classes: TinyFactory

Constant Summary collapse

CR =
"\015"
LF =
"\012"
EOL =
CR + LF

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(template, name, **opts, &blk) ⇒ Connection

:yield: mesg



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/xssh/connection.rb', line 23

def initialize(template, name, **opts, &blk) # :yield: mesg
  opts[:host_name]  ||= name
  opts[:port]       ||= 22
  opts[:prompt]     ||= /[$%#>] \z/n
  opts[:timeout]    ||= 10
  opts[:waittime]   ||= 0
  opts[:terminator] ||= LF
  opts[:ptyoptions] ||= {}
  opts[:binmode]    ||= false
  opts[:timeout]    ||= template.timeout
  opts[:log]        ||= []

  @opts      = opts
  @name      = name
  @max_retry = opts[:max_retry] || 1
  @loggers   = [@opts[:log]].flatten.uniq.reduce({}){ |a, e| a.merge(e => build_log(e) ) }

  @opts[:delegator]&.each do |name, bk|
    define_singleton_method(name, &bk)
  end

  if @opts[:relay]
    relay        = @opts[:relay]
    info         = Xssh.factory.inventory[relay]
    @opts[:port] = Net::SSH::Gateway.new(relay, nil, info)
  end

  unless (true == @opts[:binmode] or false == @opts[:binmode])
    raise ArgumentError, "Binmode option must be true or false"
  end

  if @opts[:proxy]
    opts = @opts.slice(:host, :port, :user, :password, :timeout)
    opts[:proxy] = TinyFactory.new(@opts[:proxy])

    @ssh = Net::SSH.start(nil, nil, opts)
    @close_all = true
  else

    begin
      ssh_options = opts.slice(*Net::SSH::VALID_OPTIONS)

      if @opts[:config]
        ssh_options.delete(:host_name)
        @ssh = Net::SSH.start(@opts[:host_name], nil, ssh_options)
      else
        @ssh = Net::SSH.start(name, nil, ssh_options)
      end

      @close_all  = true
    rescue TimeoutError
      raise TimeoutError, "timed out while opening a connection to the host"
    rescue
      write_log($ERROR_INFO.to_s + "\n")
      raise
    end
  end

  start_ssh_connection(&blk)
rescue StandardError => err
  retry if (@max_retry -= 1) > 0
  raise err
end

Instance Attribute Details

#channelObject (readonly)

Returns the value of attribute channel.



6
7
8
# File 'lib/xssh/connection.rb', line 6

def channel
  @channel
end

#sshObject (readonly)

Returns the value of attribute ssh.



6
7
8
# File 'lib/xssh/connection.rb', line 6

def ssh
  @ssh
end

Instance Method Details

#binmode(mode = nil) ⇒ Object



124
125
126
127
128
129
130
131
132
133
# File 'lib/xssh/connection.rb', line 124

def binmode(mode = nil)
  case mode
  when nil
    @opts[:binmode]
  when true, false
    @opts[:binmode] = mode
  else
    raise ArgumentError, "argument must be true or false"
  end
end

#binmode=(mode) ⇒ Object



135
136
137
138
139
140
141
# File 'lib/xssh/connection.rb', line 135

def binmode=(mode)
  if (true == mode or false == mode)
    @opts[:binmode] = mode
  else
    raise ArgumentError, "argument must be true or false"
  end
end

#closeObject



113
114
115
116
117
118
119
120
121
122
# File 'lib/xssh/connection.rb', line 113

def close
  @loggers.each do |_, logger|
    next if [$stdout, $stderr, nil].include?(logger)
    logger.close
  end

  @channel.close if @channel
  @channel = nil
  @ssh.close if @close_all and @ssh
end

#cmd(string, **opts) ⇒ Object

:yield: recvdata



217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/xssh/connection.rb', line 217

def cmd(string, **opts) # :yield: recvdata
  opts[:match]   ||= @opts[:prompt]
  opts[:timeout] ||= @opts[:timeout]
  opts[:faileof] ||= @opts[:faileof]

  self.puts(string)

  if block_given?
    waitfor(**opts){|c| yield c }
  else
    waitfor(**opts)
  end
end

#disable_log(log = $stdout) ⇒ Object



253
254
255
256
257
258
259
# File 'lib/xssh/connection.rb', line 253

def disable_log(log = $stdout)
  @loggers.delete(log)
  if block_given?
    yield
    enable_log(log)
  end
end

#enable_log(log = $stdout) ⇒ Object



245
246
247
248
249
250
251
# File 'lib/xssh/connection.rb', line 245

def enable_log(log = $stdout)
  @loggers.update(log => build_log(log))
  if block_given?
    yield
    disable_log(log)
  end
end

#interact!Object



231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/xssh/connection.rb', line 231

def interact!
  loop do
    com = $stdin.gets.strip

    if com == "exit"
      close
      exit 0
    else
      self.puts(com)
      waitfor
    end
  end
end


200
201
202
203
204
205
206
# File 'lib/xssh/connection.rb', line 200

def print(string)
  if @opts[:binmode]
    self.write(string)
  else
    self.write(string.gsub(/\n/n, @opts[:terminator]))
  end
end

#prompt=(val) ⇒ Object



208
209
210
# File 'lib/xssh/connection.rb', line 208

def prompt= val
  @opts[:prompt] = val
end

#puts(string) ⇒ Object



212
213
214
215
# File 'lib/xssh/connection.rb', line 212

def puts(string)
  @string = string + "\n"
  self.print(string + "\n")
end

#start_ssh_connection(&blk) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/xssh/connection.rb', line 87

def start_ssh_connection(&blk)
  @buf     = ""
  @eof     = false
  @channel = nil
  @ssh.open_channel do |channel|
    channel.on_data { |ch,data| @buf << data }
    channel.on_extended_data { |ch,type,data| @buf << data if type == 1 }
    channel.on_close { @eof = true }
    channel.request_pty(@opts[:ptyoptions]) { |ch,success|
      if success == false
        raise "Failed to open ssh pty"
      end
    }
    channel.send_channel_request("shell") { |ch, success|
      if success
        @channel = ch
        waitfor(&blk)
        return
      else
        raise "Failed to open ssh shell"
      end
    }
  end
  @ssh.loop
end

#waitfor(prompt = , **opts) ⇒ Object

:yield: recvdata



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/xssh/connection.rb', line 143

def waitfor(prompt = @opts[:prompt], **opts) # :yield: recvdata
  opts[:timeout]  ||= @opts[:timeout]
  opts[:waittime] ||= @opts[:waittime]
  opts[:faileof]  ||= @opts[:faileof]
  prompt          = Regexp.new( Regexp.quote(prompt) ) if prompt.kind_of?(String)

  opts[:timeout] = nil unless opts[:timeout]

  line = ''
  buf  = ''
  rest = ''
  sock = @ssh.transport.socket

  until @ssh.transport.socket.available == 0 && @buf == "" && prompt === line && (@eof || (!sock.closed? && !IO::select([sock], nil, nil, opts[:waittime])))
    if @buf == '' && (@ssh.transport.socket.available == 0) && !(prompt === line) && !IO::select([sock], nil, nil, opts[:timeout])
      raise Net::ReadTimeout, "timed out while waiting for more data"
    end

    _process_ssh

    if @buf != ""
      c    = @buf; @buf = ""
      buf  = rest + c
      rest = ''

      unless @opts[:binmode]
        if pt = buf.rindex(/\r\z/no)
          buf  = buf[0 ... pt]
          rest = buf[pt .. -1]
        end
        buf.gsub!(/#{EOL}/no, "\n")
      end

      line += buf

      unless buf == @string
        write_log(buf)
      end

    elsif @eof # End of file reached
      break if prompt === line
      raise EOFError if opts[:faileof]
      if line == ''
        line = nil
        yield nil if block_given?
      end
      break
    end
  end
  line
end

#write(string) ⇒ Object



195
196
197
198
# File 'lib/xssh/connection.rb', line 195

def write(string)
  @channel.send_data string
  _process_ssh
end