我可以在同一个 SSH 会话中使用 exec 和 upload 吗?

Can I use exec and upload during the same SSH session?

我需要在 ssh 会话期间执行多项操作。目前我分别使用 SSH.startSCP.start 进行远程操作和上传。这是一个例子:

Net::SSH.start(host, user, options) do |session|
  output = session.exec!(cmd)
end   

Net::SCP.start(host, user, options) do |scp|
  scp.upload!(src, dst, :recursive => true)
  scp.upload!(src1, dst1, :recursive => true)
end

Net::SSH.start(host, user, options) do |session|
  output = session.exec!(cmd)
end

问题是每次操作都需要重新建立 SSH 连接,这会影响整体性能。

有没有办法打开会话,然后执行所有必需的操作,例如命令、上传和下载?

SSH 协议允许每个连接有多个通道。所以技术上是可以的。

我不知道 Ruby net-ssh 实现,但从它的 API 来看似乎支持这个。

constructor of Net::SCP class 退出 SSH 会话。

# Creates a new Net::SCP session on top of the given Net::SSH +session+
# object.
def initialize(session)

因此,将您现有的 Net::SSH 实例传递给 Net::SCP 构造函数,而不是使用 .start 方法启动新会话。