tags:

views:

45

answers:

5

I have the following script:

#!/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

and i get /root, instead of /var/example/engines/

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

That will execute the cd command, then the pwd command in the new directory.

I'm not a ruby guy, but I'm going to guess there are probably more elegant solutions.

haydenmuhl
A: 

Im not a ruby programmer, but you could try to concatenate your commands with ; or &&

Johan
A: 

see if there's something analogous to the file(utils?) cd block syntax, otherwise just run the command in the same subshell, e.g. ssh.exec "cd /var/example/engines/; pwd" ?

nruth
A: 

In Net::SSH, #exec & #exec! are the same, e.g. they execute a command (with the exceptions that exec! blocks other calls until it's done). The key thing to remember is that Net::SSH essentially runs every command from the user's directory when using exec/exec!. So, in your code, you are running cd /some/path from the /root directory and then pwd - again from the /root directory.

The simplest way I know how to run multiple commands in sequence is to chain them together with && (as mentioned above by other posters). So, it would look something like this:

#!/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

Unfortunately, the Net::SSH shell service was removed in version 2.

Brian
A: 

There used to have a shell service which allow stateful command like your trying to do in net/ssh v1 but it has been remove in v2. However there's a side project of the author of net/ssh that allows you to do that. Have a look here: http://github.com/jamis/net-ssh-shell

hellvinz