4. Executing Commands

4.1. Using Channels

To run multiple processes in parallel, you can access the channel API directly, setting up multiple channels and callbacks in order to process the output from the channel.

Suppose, for example, that you wanted to run multiple “tail” commands on various logs on the remote machine, combining them all into the output on the client. Something like the following would suffice:

Running "tail" on multiple remote files [ruby]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def do_tail( session, file )
  session.open_channel do |channel|
    channel.on_data do |ch, data|
      puts "[#{file}] -> #{data}"
    end
    channel.exec "tail -f #{file}"
  end
end

Net::SSH.start( 'host' ) do |session|
  do_tail session, "/var/log/messages"
  do_tail session, "/var/log/XFree86.0.log"
  do_tail session, "/var/log/tomcat/catalina.log"
  do_tail session, "/var/log/mysql/mysql.err"
  session.loop
end

As you can see, four different logs are tailed on four separate channels. Each channel registers an on_data callback (which simply displays the data it recieves, together with the name of the log file it came from). The exec method of the channel is then invoked, which simply sends the request to execute the process to the server, and then returns.

The loop method then blocks while packets and processed and callbacks are invoked, completing the program.

This approach works fine for processing data coming from the server, and with a little work and coordination can work well for sending data to the server as well, by calling the send_data method of the channel at the appropriate times. However, it requires a bit of forethought, since you have to come up with a simple state machine to manage most interactive sessions, and many times that’s more effort than it is worth.

4.2. Using #process.open

The #process.open interface provides a simpler way to manage interactive sessions. It still works via callbacks, and it still requires a kind of state machine in order to process input, but it does simplify things a little bit.

Just open an SSH session. The #process service of the session manages access to convenience methods for handling and communicating with remote processes. In particular the #open method of the #process service allows you to constuct callbacks for dealing with remote processes, more conveniently than using channels directly.

Consider the “bc” command. It is a command-line calculator that accepts expressions on stdin and writes the results to stdout. When it encounters the word quit on the input, it exits. Sounds like a great way to demonstrate the process service…

Using #process.open [ruby]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Net::SSH.start( 'host' ) do |session|

  session.process.open( "bc" ) do |bc|
    dialog = [ "5+5", "7*12", "sqrt(2.000000)", "quit" ]

    bc.on_success do |p|
      puts "requesting result of #{dialog.first}"
      p.puts dialog.shift
    end

    bc.on_stdout do |p,data|
      puts "--> #{data}"
      unless dialog.empty?
        puts "requesting result of #{dialog.first}"
        p.puts dialog.shift
      end
    end

 bc.on_exit do |p, status|
      puts "process finished with exit status: #{status}"
    end
  end

end

Notice the progression. First, the session itself is started. Then, while the session is active, the process is invoked (via #process.open). After we have a handle to the process (which is yielded to the block, in this case), we set up the callbacks on the process. These are reminiscent of, but different from, the callbacks that we set up on the channel itself in the previous section.

The following callbacks are defined for a process handle:

Name Description
on_exit This callback is invoked when the process terminates normally. The block should accept two parameters: the process handle itself, and the exit status of the process.
on_failure This callback is invoked when the process could not be invoked. It should take two parameters: the process handle itself, and a status string (which currently always nil).
on_success This callback is invoked after the process has been successfully started. The callback should take a single parameter: the process handle itself.
on_stderr This callback is invoked when data is received from the process’s stderr stream. The callback should have two parameters: the process handle, and the data.
on_stdout This callback is invoked when data is received from the process’s stdout stream. The callback should have two parameters: the process handle, and the data.

Sending data to the process is as simple as calling puts on the process handle. If you don’t want a newline appended to your data, use write instead.

Notice that, when sending a block to #process.open, you do not have to explicitly invoke session.loop. It is implicitly called at the end of the block. If you ever want to set up multiple processes to run in parallel, simply use #process.open without a block. The process handle will be returned, and you will be required to execute session.loop manually.

For more information on the #process.open service, see the API documentation for Net::SSH::Service::Process::Open.

4.3. Using #process.popen3

The last approach to interacting with remote processes is the #popen3 method of #process service. It is a synchronous approach, meaning that each method call may (potentially) block until data is received; you can’t be using other features of the Net::SSH package while using it, but you don’t have to mess with callbacks.

If you are familiar with the “popen3” Ruby module, this will seem familiar. It’s not a perfect clone of the “popen3” module’s functionality, but it’s close. What you do is you specify the process to invoke, and then you get three pseudo-IO objects back: the process’s input stream, it’s output stream, and it’s error stream. You can write to the input stream to send data to the process, or read from the output and error streams. Reading from the output or error streams will block until data is available, which makes it very convenient for interacting with a single remote process.

Here’s the previous “bc” example, rewritten to use #popen3:

Using #process.popen3 [ruby]
1
2
3
4
5
6
7
8
9
10
11
12
Net::SSH.start( 'host' ) do |session|

  input, output, error = session.process.popen3( "bc" )

  [ "5+5", "7*12", "sqrt(2.000000)" ].each do |formula|
    input.puts formula
    puts "#{formula}=#{output.read}"
  end

  input.puts "quit"

end

Much more concise, isn’t it? One caveat, though: there is no way to kill the process (unless the process can terminate itself, such as through the use of issuing bc’s “quit” command as used above) without closing the session. To remedy this, there is also a block version of popen3 that provides an explicit scope for the three data streams:

Transactional form of #process.popen3 [ruby]
1
2
3
4
5
6
7
8
Net::SSH.start( 'host' ) do |session|
  session.process.popen3( "bc" ) do |input, output, error|
    [ "5+5", "7*12", "sqrt(2.000000)" ].each do |formula|
      input.puts formula
 puts "#{formula}=#{output.read}"
    end
  end
end

The three streams will be closed and process explicitly terminated when the block ends.