Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i execute 2 or more commands in the same ssh session?

Tags:

ruby

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/

like image 839
kamal Avatar asked Sep 08 '10 19:09

kamal


People also ask

How do you run two commands together?

Running Multiple Commands as a Single Job We can start multiple commands as a single job through three steps: Combining the commands – We can use “;“, “&&“, or “||“ to concatenate our commands, depending on the requirement of conditional logic, for example: cmd1; cmd2 && cmd3 || cmd4.

How do I run multiple commands on one Linux server?

To run commands on multiple servers, add the servers to a hosts file as explained before. Then run pdsh as shown; the flag -w is used to specify the hosts file, and -R is used to specify the remote command module (available remote command modules include ssh, rsh, exec, the default is rsh).

How do I run two Unix commands at the same time?

Sometimes you might want to execute a second command only if the first command does not succeed. To do this, we use the logical OR operator, or two vertical bars ( || ). For example, we want to check to see if the MyFolder directory exists ( [ -d ~/MyFolder ] ) and create it if it doesn't ( mkdir ~/MyFolder ).


2 Answers

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.

like image 159
haydenmuhl Avatar answered Oct 14 '22 03:10

haydenmuhl


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.

like image 32
Brian Avatar answered Oct 14 '22 04:10

Brian