我如何在同一个ssh会话中执行2个或更多的命令?

我有以下脚本:

#!/usr/bin/env ruby
require 'rubygems'
require 'net/ssh'

Net::SSH.start('host1', 'root', :password => "mypassword1") do |ssh|
    stdout = ""

    ssh.exec("cd /var/example/engines/")
    ssh.exec!( "pwd" ) do |channel, stream, data|
        stdout << data if stream == :stdout
    end
    puts stdout

    ssh.loop
end

我得到/root ,而不是/var/example/engines/


看看是否有类似于文件(utils?)cd块语法的东西,否则只需在同一个子shell中运行命令,例如ssh.exec“cd / var / example / engines /; pwd”?


ssh.exec("cd /var/example/engines/; pwd")

这将执行cd命令,然后执行新目录中的pwd命令。

我不是一个红宝石的家伙,但我会猜测可能有更优雅的解决方案。


在Net :: SSH中, #exec#exec! 是相同的,例如他们执行一个命令(除了exec!阻止其他调用,直到它完成)。 关键要记住的是,当使用exec / exec!时,Net :: SSH实质上运行用户目录中的每个命令。 因此,在您的代码中,您正在从/root目录运行cd /some/path ,然后再从/root目录运行pwd

我知道如何按顺序运行多个命令最简单的方法是用&&(如上面提到的其他海报)将它们链接在一起。 所以,它看起来像这样:

#!/usr/bin/env ruby
require 'rubygems'
require 'net/ssh'

Net::SSH.start('host1', 'root', :password => "mypassword1") do |ssh|
    stdout = ""

    ssh.exec!( "cd /var/example/engines/ && pwd" ) do |channel, stream, data|
        stdout << data if stream == :stdout
    end
    puts stdout

    ssh.loop
end

不幸的是,Net :: SSH shell服务在版本2中被删除。

链接地址: http://www.djcxy.com/p/25267.html

上一篇: How can i execute 2 or more commands in the same ssh session?

下一篇: Git: what is a dangling commit/blob and where do they come from?