Skip to content

Instantly share code, notes, and snippets.

@IndigoCZ
Created June 29, 2012 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IndigoCZ/3018233 to your computer and use it in GitHub Desktop.
Save IndigoCZ/3018233 to your computer and use it in GitHub Desktop.
Test: SSH Connection with multiple execs
#!/usr/bin/env ruby
$VERBOSE=nil
require 'rubygems'
require 'net/ssh'
require 'logger'
logger=Logger.new(STDOUT)
Net::SSH.start( 'localhost', `whoami`.chomp) do |ssh|
rc, stdout, stderr = 0, "", ""
last_out, last_err = "", ""
ssh.open_channel do |channel| # open the SSH channel
channel.on_request("exit-status") do |ch, data| # handle the return code
logger.info last_out unless last_out == ""
logger.warn last_err unless last_err == ""
rc = data.read_long.to_i
ch.close # process finished, close the channel
end
channel.on_data do |ch, data| # handle STDOUT output
stdout << data
last_out << data
logger.debug(data)
if data[-1]=="\n"
logger.info(last_out.chomp) unless block_given?
last_out = ""
end
end
channel.on_extended_data do |ch, type, data| # handle STDERR output
options[:stderr_to_stdout] ? stdout << data : stderr << data # store error where appropriate
last_err << data
if data[-1]=="\n"
logger.warn(last_err.chomp) unless block_given?
last_err = ""
end
end
channel.exec "var='foo'; echo Value: $var"
channel.exec "echo Value: $var"
ssh.loop # wait for the SSH channel to close
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment