如何SSH交互式会话

今天是个好日子

我需要在linux机器上执行命令这个命令是交互式命令。 交互式命令意味着需要输入[yes,no]或两次密码

我的真实案例是。 我创建了一个脚本执行命令并成功获取输出。 但有些服务器的登录密码已过期,所以我需要与服务器进行交互才能发送当前密码+新密码(两次)

ssh userName@10.0.0.243 userName@10.0.0.243's password: You are required to change your password immediately (password aged) Last login: Sun Aug 7 13:15:40 2011 from 10.0.0.28 WARNING: Your password has expired. You must change your password now and login again! Changing password for user userName. Changing password for userName (current) UNIX password: New UNIX password: Retype new UNIX password: 

笔记::

  • 我正在使用Ruby 1.9.2
  • 在正常情况下我执行命令没问题
  • 请,我必须避免像(echo“pass”| ssh -S)这样的变通办法让我通过任何其他互动情况。
  • 我正在使用’net / ssh’libs
  • 附带脚本http://king-sabri.net/files/LinuxHWScanner.rb
  • 我试过“net / ssh / telnet”并没有帮助
  • 一些建议说使用’rake / remote_task’是解决方案,但我无法理解它在我的情况下是如何工作的

如果你需要更简单,这里有一个简单的代码,如果你让它工作,我会解决我以前的问题

  require 'net/ssh' host = "10.0.0.106" port = 22 # SSH port user = 'root' # username pass = "123123" # password Net::SSH.start( host,user,:password => pass, :port=> port , :verbose => :error ) do |session| puts session.exec!("passwd root") end 

像这样的东西?

 Net::SSH.start('10.0.0.6', 'not_root', :password => "test") do |ssh| ssh.open_channel do |channel| channel.on_request "exit-status" do |channel, data| $exit_status = data.read_long end channel.exec("passwd") do |channel, success| if success channel.on_data do |channel, data| # Don't really need this callback actually puts "got data: #{data.inspect}" end # You don't need this line if you're root channel.send_data("oldpass\n") channel.send_data("newpass\n") channel.send_data("newpass\n") else puts "FAILED" end end channel.wait puts "SUCCESS" if $exit_status == 0 end end 

这个很脏,但是在过早的过期提示和passwd发布时都适用:

 Net::SSH.start('localhost', 'not_root', :password => "test") do |ssh| ssh.open_channel do |channel| channel.on_request "exit-status" do |channel, data| $exit_status = data.read_long end channel.on_data do |channel, data| puts data.inspect if data.inspect.include? "current" channel.send_data("oldpass\n"); elsif data.inspect.include? "new" channel.send_data("newpass\n"); end end channel.request_pty # This will just safely fail if we have already a password prompt on channel.exec("passwd"); channel.wait # Will reflect a valid status in both cases puts $exit_status end end