Class: Chef::Knife::Ssh

Inherits:
Chef::Knife show all
Includes:
Mixin::ShellOut
Defined in:
lib/chef/knife/ssh.rb

Constant Summary

Constants included from Mixin::ShellOut

Mixin::ShellOut::DEPRECATED_OPTIONS

Instance Attribute Summary collapse

Attributes inherited from Chef::Knife

#name_args, #ui

Instance Method Summary collapse

Methods included from Mixin::ShellOut

#run_command_compatible_options, #shell_out, #shell_out!, #shell_out_with_systems_locale, #shell_out_with_systems_locale!

Methods inherited from Chef::Knife

#api_key, #apply_computed_config, category, chef_config_dir, common_name, #config_file_settings, config_loader, #configure_chef, #create_object, #delete_object, dependency_loaders, deps, #format_rest_error, guess_category, #humanize_exception, #humanize_http_exception, inherited, #initialize, load_commands, load_config, load_deps, #maybe_setup_fips, #merge_configs, msg, #noauth_rest, #parse_options, reset_config_loader!, reset_subcommands!, #rest, run, #run_with_pretty_exceptions, #server_url, #show_usage, snake_case_name, subcommand_category, subcommand_class_from, subcommand_files, subcommand_loader, subcommands, subcommands_by_category, #test_mandatory_field, ui, unnamed?, use_separate_defaults?, #username

Methods included from Mixin::ConvertToClassName

#constantize, #convert_to_class_name, #convert_to_snake_case, #filename_to_qualified_string, #normalize_snake_case_name, #snake_case_basename

Methods included from Mixin::PathSanity

#enforce_path_sanity

Constructor Details

This class inherits a constructor from Chef::Knife

Instance Attribute Details

#password=(value) ⇒ Object (writeonly)

Sets the attribute password

Parameters:

  • value

    the value to set the attribute password to.



39
40
41
# File 'lib/chef/knife/ssh.rb', line 39

def password=(value)
  @password = value
end

Instance Method Details

#configure_gatewayObject



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/chef/knife/ssh.rb', line 146

def configure_gateway
  config[:ssh_gateway] ||= Chef::Config[:knife][:ssh_gateway]
  if config[:ssh_gateway]
    gw_host, gw_user = config[:ssh_gateway].split("@").reverse
    gw_host, gw_port = gw_host.split(":")
    gw_opts = session_options(gw_host, gw_port, gw_user)
    user = gw_opts.delete(:user)

    begin
      # Try to connect with a key.
      session.via(gw_host, user, gw_opts)
    rescue Net::SSH::AuthenticationFailed
      prompt = "Enter the password for #{user}@#{gw_host}: "
      gw_opts[:password] = prompt_for_password(prompt)
      # Try again with a password.
      session.via(gw_host, user, gw_opts)
    end
  end
end

#configure_passwordObject

This is a bit overly complicated because of the way we want knife ssh to work with -P causing a password prompt for the user, but we have to be conscious that this code gets included in knife bootstrap and knife * server create as well. We want to change the semantics so that the default is false and ‘nil’ means -P without an argument on the command line. But the other utilities expect nil to be the default and we can’t prompt in that case. So we effectively use ssh_password_ng to determine if we’re coming from knife ssh or from the other utilities. The other utilties can also be patched to use ssh_password_ng easily as long they follow the convention that the default is false.



513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
# File 'lib/chef/knife/ssh.rb', line 513

def configure_password
  if config.has_key?(:ssh_password_ng) && config[:ssh_password_ng].nil?
    # If the parameter is called on the command line with no value
    # it will set :ssh_password_ng = nil
    # This is where we want to trigger a prompt for password
    config[:ssh_password] = get_password
  else
    # if ssh_password_ng is false then it has not been set at all, and we may be in knife ec2 and still
    # using an old config[:ssh_password].  this is backwards compatibility.  all knife cloud plugins should
    # be updated to use ssh_password_ng with a default of false and ssh_password should be retired, (but
    # we'll still need to use the ssh_password out of knife.rb if we find that).
    ssh_password = config.has_key?(:ssh_password_ng) ? config[:ssh_password_ng] : config[:ssh_password]
    # Otherwise, the password has either been specified on the command line,
    # in knife.rb, or key based auth will be attempted
    config[:ssh_password] = get_stripped_unfrozen_value(ssh_password ||
                       Chef::Config[:knife][:ssh_password])
  end
end

#configure_sessionObject



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/chef/knife/ssh.rb', line 166

def configure_session
  list = config[:manual] ?
         @name_args[0].split(" ") :
         search_nodes
  if list.length == 0
    if @action_nodes.length == 0
      ui.fatal("No nodes returned from search")
    else
      ui.fatal("#{@action_nodes.length} #{@action_nodes.length > 1 ? "nodes" : "node"} found, " +
               "but does not have the required attribute to establish the connection. " +
               "Try setting another attribute to open the connection using --attribute.")
    end
    exit 10
  end
  session_from_list(list)
end

#configure_ssh_identity_fileObject



532
533
534
535
# File 'lib/chef/knife/ssh.rb', line 532

def configure_ssh_identity_file
  # config[:identity_file] is DEPRECATED in favor of :ssh_identity_file
  config[:ssh_identity_file] = get_stripped_unfrozen_value(config[:ssh_identity_file] || config[:identity_file] || Chef::Config[:knife][:ssh_identity_file])
end

#configure_userObject



502
503
504
505
# File 'lib/chef/knife/ssh.rb', line 502

def configure_user
  config[:ssh_user] = get_stripped_unfrozen_value(config[:ssh_user] ||
                       Chef::Config[:knife][:ssh_user])
end

#csshObject



473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
# File 'lib/chef/knife/ssh.rb', line 473

def cssh
  cssh_cmd = nil
  %w{csshX cssh}.each do |cmd|
    begin
      # Unix and Mac only
      cssh_cmd = shell_out!("which #{cmd}").stdout.strip
      break
    rescue Mixlib::ShellOut::ShellCommandFailed
    end
  end
  raise Chef::Exceptions::Exec, "no command found for cssh" unless cssh_cmd

  # pass in the consolidated identity file option to cssh(X)
  if config[:ssh_identity_file]
    cssh_cmd << " --ssh_args '-i #{File.expand_path(config[:ssh_identity_file])}'"
  end

  session.servers_for.each do |server|
    cssh_cmd << " #{server.user ? "#{server.user}@#{server.host}" : server.host}"
  end
  Chef::Log.debug("Starting cssh session with command: #{cssh_cmd}")
  exec(cssh_cmd)
end

#extract_nested_value(data_structure, path_spec) ⇒ Object



537
538
539
# File 'lib/chef/knife/ssh.rb', line 537

def extract_nested_value(data_structure, path_spec)
  ui.presenter.extract_nested_value(data_structure, path_spec)
end

#fixup_sudo(command) ⇒ Object



282
283
284
# File 'lib/chef/knife/ssh.rb', line 282

def fixup_sudo(command)
  command.sub(/^sudo/, 'sudo -p \'knife sudo password: \'')
end

#get_passwordObject



334
335
336
# File 'lib/chef/knife/ssh.rb', line 334

def get_password
  @password ||= prompt_for_password
end

#get_ssh_attribute(node) ⇒ Object



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/chef/knife/ssh.rb', line 183

def get_ssh_attribute(node)
  # Order of precedence for ssh target
  # 1) command line attribute
  # 2) configuration file
  # 3) cloud attribute
  # 4) fqdn
  if config[:attribute]
    Chef::Log.debug("Using node attribute '#{config[:attribute]}' as the ssh target")
    attribute = config[:attribute]
  elsif Chef::Config[:knife][:ssh_attribute]
    Chef::Log.debug("Using node attribute #{Chef::Config[:knife][:ssh_attribute]}")
    attribute = Chef::Config[:knife][:ssh_attribute]
  elsif node[:cloud] &&
      node[:cloud][:public_hostname] &&
      !node[:cloud][:public_hostname].empty?
    Chef::Log.debug("Using node attribute 'cloud[:public_hostname]' automatically as the ssh target")
    attribute = "cloud.public_hostname"
  else
    # falling back to default of fqdn
    Chef::Log.debug("Using node attribute 'fqdn' as the ssh target")
    attribute = "fqdn"
  end
  attribute
end

#get_stripped_unfrozen_value(value) ⇒ Object



497
498
499
500
# File 'lib/chef/knife/ssh.rb', line 497

def get_stripped_unfrozen_value(value)
  return nil if value.nil?
  value.strip
end

#interactiveObject



367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
# File 'lib/chef/knife/ssh.rb', line 367

def interactive
  puts "Connected to #{ui.list(session.servers_for.collect { |s| ui.color(s.host, :cyan) }, :inline, " and ")}"
  puts
  puts "To run a command on a list of servers, do:"
  puts "  on SERVER1 SERVER2 SERVER3; COMMAND"
  puts "  Example: on latte foamy; echo foobar"
  puts
  puts "To exit interactive mode, use 'quit!'"
  puts
  loop do
    command = read_line
    case command
    when "quit!"
      puts "Bye!"
      break
    when /^on (.+?); (.+)$/
      raw_list = $1.split(" ")
      server_list = Array.new
      session.servers.each do |session_server|
        server_list << session_server if raw_list.include?(session_server.host)
      end
      command = $2
      ssh_command(command, session.on(*server_list))
    else
      ssh_command(command)
    end
  end
end

#mactermObject



449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'lib/chef/knife/ssh.rb', line 449

def macterm
  begin
    require "appscript"
  rescue LoadError
    STDERR.puts "You need the rb-appscript gem to use knife ssh macterm. `(sudo) gem install rb-appscript` to install"
    raise
  end

  Appscript.app("/Applications/Utilities/Terminal.app").windows.first.activate
  Appscript.app("System Events").application_processes["Terminal.app"].keystroke("n", :using => :command_down)
  term = Appscript.app("Terminal")
  window = term.windows.first.get

  (session.servers_for.size - 1).times do |i|
    window.activate
    Appscript.app("System Events").application_processes["Terminal.app"].keystroke("t", :using => :command_down)
  end

  session.servers_for.each_with_index do |server, tab_number|
    cmd = "unset PROMPT_COMMAND; echo -e \"\\033]0;#{server.host}\\007\"; ssh #{server.user ? "#{server.user}@#{server.host}" : server.host}"
    Appscript.app("Terminal").do_script(cmd, :in => window.tabs[tab_number + 1].get)
  end
end


286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# File 'lib/chef/knife/ssh.rb', line 286

def print_data(host, data)
  @buffers ||= {}
  if leftover = @buffers[host]
    @buffers[host] = nil
    print_data(host, leftover + data)
  else
    if newline_index = data.index("\n")
      line = data.slice!(0...newline_index)
      data.slice!(0)
      print_line(host, line)
      print_data(host, data)
    else
      @buffers[host] = data
    end
  end
end


303
304
305
306
307
# File 'lib/chef/knife/ssh.rb', line 303

def print_line(host, data)
  padding = @longest - host.length
  str = ui.color(host, :cyan) + (" " * (padding + 1)) + data
  ui.msg(str)
end

#prompt_for_password(prompt = "Enter your password: ") ⇒ Object



338
339
340
# File 'lib/chef/knife/ssh.rb', line 338

def prompt_for_password(prompt = "Enter your password: ")
  ui.ask(prompt) { |q| q.echo = false }
end

#read_lineObject

Present the prompt and read a single line from the console. It also detects ^D and returns “exit” in that case. Adds the input to the history, unless the input is empty. Loops repeatedly until a non-empty line is input.



346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/chef/knife/ssh.rb', line 346

def read_line
  loop do
    command = reader.readline("#{ui.color('knife-ssh>', :bold)} ", true)

    if command.nil?
      command = "exit"
      puts(command)
    else
      command.strip!
    end

    unless command.empty?
      return command
    end
  end
end

#readerObject



363
364
365
# File 'lib/chef/knife/ssh.rb', line 363

def reader
  Readline
end

#runObject



541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
# File 'lib/chef/knife/ssh.rb', line 541

def run
  @longest = 0

  configure_user
  configure_password
  configure_ssh_identity_file
  configure_gateway
  configure_session

  exit_status =
  case @name_args[1]
  when "interactive"
    interactive
  when "screen"
    screen
  when "tmux"
    tmux
  when "macterm"
    macterm
  when "cssh"
    cssh
  when "csshx"
    Chef::Log.warn("knife ssh csshx will be deprecated in a future release")
    Chef::Log.warn("please use knife ssh cssh instead")
    cssh
  else
    ssh_command(@name_args[1..-1].join(" "))
  end

  session.close
  if exit_status != 0
    exit exit_status
  else
    exit_status
  end
end

#screenObject



396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# File 'lib/chef/knife/ssh.rb', line 396

def screen
  tf = Tempfile.new("knife-ssh-screen")
  Chef::Util::PathHelper.home(".screenrc") do |screenrc_path|
    if File.exist? screenrc_path
      tf.puts("source #{screenrc_path}")
    end
  end
  tf.puts("caption always '%-Lw%{= BW}%50>%n%f* %t%{-}%+Lw%<'")
  tf.puts("hardstatus alwayslastline 'knife ssh #{@name_args[0]}'")
  window = 0
  session.servers_for.each do |server|
    tf.print("screen -t \"#{server.host}\" #{window} ssh ")
    tf.print("-i #{config[:ssh_identity_file]} ") if config[:ssh_identity_file]
    server.user ? tf.puts("#{server.user}@#{server.host}") : tf.puts(server.host)
    window += 1
  end
  tf.close
  exec("screen -c #{tf.path}")
end

#sessionObject



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/chef/knife/ssh.rb', line 130

def session
  config[:on_error] ||= :skip
  ssh_error_handler = Proc.new do |server|
    case config[:on_error]
    when :skip
      ui.warn "Failed to connect to #{server.host} -- #{$!.class.name}: #{$!.message}"
      $!.backtrace.each { |l| Chef::Log.debug(l) }
    when :raise
      #Net::SSH::Multi magic to force exception to be re-raised.
      throw :go, :raise
    end
  end

  @session ||= Net::SSH::Multi.start(:concurrent_connections => config[:concurrency], :on_error => ssh_error_handler)
end

#session_from_list(list) ⇒ Object



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/chef/knife/ssh.rb', line 260

def session_from_list(list)
  list.each do |item|
    host, ssh_port = item
    Chef::Log.debug("Adding #{host}")
    session_opts = session_options(host, ssh_port)
    # Handle port overrides for the main connection.
    session_opts[:port] = Chef::Config[:knife][:ssh_port] if Chef::Config[:knife][:ssh_port]
    session_opts[:port] = config[:ssh_port] if config[:ssh_port]
    # Handle connection timeout
    session_opts[:timeout] = Chef::Config[:knife][:ssh_timeout] if Chef::Config[:knife][:ssh_timeout]
    session_opts[:timeout] = config[:ssh_timeout] if config[:ssh_timeout]
    # Create the hostspec.
    hostspec = session_opts[:user] ? "#{session_opts.delete(:user)}@#{host}" : host
    # Connect a new session on the multi.
    session.use(hostspec, session_opts)

    @longest = host.length if host.length > @longest
  end

  session
end

#session_options(host, port, user = nil) ⇒ Hash<Symbol, Object>

Net::SSH session options hash for global options. These should be options that will apply to the gateway connection in addition to the main one.

Parameters:

  • host (String)

    Hostname for this session.

  • port (String)

    SSH port for this session.

  • user (String) (defaults to: nil)

    Optional username for this session.

Returns:

Since:

  • 12.5.0



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/chef/knife/ssh.rb', line 236

def session_options(host, port, user = nil)
  ssh_config = Net::SSH.configuration_for(host)
  {}.tap do |opts|
    # Chef::Config[:knife][:ssh_user] is parsed in #configure_user and written to config[:ssh_user]
    opts[:user] = user || config[:ssh_user] || ssh_config[:user]
    if config[:ssh_identity_file]
      opts[:keys] = File.expand_path(config[:ssh_identity_file])
      opts[:keys_only] = true
    elsif config[:ssh_password]
      opts[:password] = config[:ssh_password]
    end
    # Don't set the keys to nil if we don't have them.
    forward_agent = config[:forward_agent] || ssh_config[:forward_agent]
    opts[:forward_agent] = forward_agent unless forward_agent.nil?
    port ||= ssh_config[:port]
    opts[:port] = port unless port.nil?
    opts[:logger] = Chef::Log.logger if Chef::Log.level == :debug
    if !config[:host_key_verify]
      opts[:paranoid] = false
      opts[:user_known_hosts_file] = "/dev/null"
    end
  end
end

#ssh_command(command, subsession = nil) ⇒ Object



309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'lib/chef/knife/ssh.rb', line 309

def ssh_command(command, subsession = nil)
  exit_status = 0
  subsession ||= session
  command = fixup_sudo(command)
  command.force_encoding("binary") if command.respond_to?(:force_encoding)
  subsession.open_channel do |ch|
    ch.request_pty
    ch.exec command do |ch, success|
      raise ArgumentError, "Cannot execute #{command}" unless success
      ch.on_data do |ichannel, data|
        print_data(ichannel[:host], data)
        if data =~ /^knife sudo password: /
          print_data(ichannel[:host], "\n")
          ichannel.send_data("#{get_password}\n")
        end
      end
      ch.on_request "exit-status" do |ichannel, data|
        exit_status = [exit_status, data.read_long].max
      end
    end
  end
  session.loop
  exit_status
end

#tmuxObject



416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# File 'lib/chef/knife/ssh.rb', line 416

def tmux
  ssh_dest = lambda do |server|
    identity = "-i #{config[:ssh_identity_file]} " if config[:ssh_identity_file]
    prefix = server.user ? "#{server.user}@" : ""
    "'ssh #{identity}#{prefix}#{server.host}'"
  end

  new_window_cmds = lambda do
    if session.servers_for.size > 1
      [""] + session.servers_for[1..-1].map do |server|
        if config[:tmux_split]
          "split-window #{ssh_dest.call(server)}; tmux select-layout tiled"
        else
          "new-window -a -n '#{server.host}' #{ssh_dest.call(server)}"
        end
      end
    else
      []
    end.join(" \\; ")
  end

  tmux_name = "'knife ssh #{@name_args[0].tr(':', '=')}'"
  begin
    server = session.servers_for.first
    cmd = ["tmux new-session -d -s #{tmux_name}",
           "-n '#{server.host}'", ssh_dest.call(server),
           new_window_cmds.call].join(" ")
    shell_out!(cmd)
    exec("tmux attach-session -t #{tmux_name}")
  rescue Chef::Exceptions::Exec
  end
end