使用session.exec时Ruby Net :: SFTP错误

时间:2013-01-23 23:17:17

标签: ruby net-ssh net-sftp

我在Ruby中遇到Net::SFTP的一些意外行为(ruby 1.9.3p194)。

变体#1 失败。它启动SFTP块并使用session.exec!运行shell命令。

Net::SFTP.start(...) do |sftp|
  sftp.session.exec! "mkdir -p ..."  # Fails here.
  sftp.upload!(...)
end

变体#2 成功。它启动一个SSH块并使用sftp.upload!复制文件。

Net::SSH.start(...)  do |ssh|
  ssh.exec! "mkdir -p ..."
  ssh.sftp.upload!(...)
end

任何想法或解释都将不胜感激。

以下是变体#1的堆栈跟踪:

can't add a new key into hash during iteration

net-ssh-2.6.3/lib/net/ssh/connection/session.rb:296:in `[]='
net-ssh-2.6.3/lib/net/ssh/connection/session.rb:296:in `open_channel'
net-ssh-2.6.3/lib/net/ssh/connection/session.rb:320:in `exec'
net-ssh-2.6.3/lib/net/ssh/connection/session.rb:354:in `exec!'
dor-services-3.20.0/lib/dor/services/digital_stacks_service.rb:28:in `block in transfer_to_document_store'
net-sftp-2.0.5/lib/net/sftp/session.rb:939:in `call'
net-sftp-2.0.5/lib/net/sftp/session.rb:939:in `block in do_version'
net-sftp-2.0.5/lib/net/sftp/session.rb:939:in `each'
net-sftp-2.0.5/lib/net/sftp/session.rb:939:in `do_version'
net-sftp-2.0.5/lib/net/sftp/session.rb:909:in `when_channel_polled'
net-ssh-2.6.3/lib/net/ssh/connection/channel.rb:311:in `call'
net-ssh-2.6.3/lib/net/ssh/connection/channel.rb:311:in `process'
net-ssh-2.6.3/lib/net/ssh/connection/session.rb:214:in `block in preprocess'
net-ssh-2.6.3/lib/net/ssh/connection/session.rb:214:in `each'
net-ssh-2.6.3/lib/net/ssh/connection/session.rb:214:in `preprocess'
net-ssh-2.6.3/lib/net/ssh/connection/session.rb:197:in `process'
net-ssh-2.6.3/lib/net/ssh/connection/session.rb:161:in `block in loop'
net-ssh-2.6.3/lib/net/ssh/connection/session.rb:161:in `loop'
net-ssh-2.6.3/lib/net/ssh/connection/session.rb:161:in `loop'
net-sftp-2.0.5/lib/net/sftp/session.rb:802:in `loop'
net-sftp-2.0.5/lib/net/sftp/session.rb:787:in `connect!'
net-sftp-2.0.5/lib/net/sftp.rb:32:in `start'

1 个答案:

答案 0 :(得分:1)

这是我为解决这个问题所写的代码:

def mkdir_p(sftp, path)
  memo = "/"
  # [0..-2] to skip the filename
  path.split("/")[0..-2].each do |dir|
    next if dir.empty?
    if sftp.dir.entries(memo).map { |entry| entry.name }.include?(dir)
      memo += "/#{dir}"
    else
      memo += "/#{dir}"
      puts "Creating the following directory: #{memo}"
      sftp.mkdir!(memo)
    end
  end
end