fork download
  1. #!/usr/bin/env ruby
  2.  
  3. require "rubygems"
  4. require "net/ssh"
  5.  
  6. @ssh = Net::SSH.start("192.168.0.10", "user", {:password => "user"})
  7.  
  8. @command_executed = false
  9.  
  10. @ssh.open_channel do |channel|
  11. channel.request_pty
  12.  
  13. #callback
  14. channel.on_data do |channel, stdout_data|
  15. if stdout_data =~ /assword:/
  16. channel.send_data "root_pass" + "\n"
  17. elsif !@su_command_executed
  18. channel.send_data "whoami" + "\n"
  19. @command_executed = true
  20. else
  21. print stdout_data
  22.  
  23. # channel.eof! でSSHのチャンネルが切れない
  24. channel.eof!
  25. end
  26.  
  27. # これだと
  28. #
  29. # whoami
  30. # root
  31. # root@cl1:~#
  32. #
  33. # の出力が無限に出続ける
  34. #
  35. # su - でrootになって一回コマンド実行して、stdout/stderr/戻り値をもらってチャンネル閉じたい
  36. puts stdout_data
  37. end
  38.  
  39. channel.exec "LANG=C su -"
  40. end
  41.  
  42. @ssh.loop
  43.  
  44. @ssh.close
  45.  
Runtime error #stdin #stdout #stderr 0.03s 32816KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- net/ssh (LoadError)
	from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
	from prog.rb:4:in `<main>'