Create a gist now

Instantly share code, notes, and snippets.

anonymous /ssh_example.rb Secret
Created Jun 29, 2012

Interactive SSH Example w/ multiple channels
$VERBOSE=nil
require 'rubygems'
require 'net/ssh'
require 'logger'
logger=Logger.new(STDOUT)
Net::SSH.start('localhost', `whoami`.chomp, password: "<YOUR PASSWORD>") do |ssh|
ssh.open_channel do |channel| # open the SSH channel
channel.exec "psql -U SOME_USER -W" do |ch, success| # execute the remote command
channel.on_request("exit-status") do |ch, data| # handle the return code
rc = data.read_long.to_i
puts "Got return code: #{rc}"
ssh.open_channel do |c|
c.exec 'pwd' do |ch|
c.on_data do |ch, data|
puts "PWD: #{data}"
end
end
end
end
channel.on_data do |ch, data| # handle STDOUT output
puts "OUT: #{data}"
logger.debug(data)
end
channel.on_extended_data do |ch, type, data| # handle STDERR output
puts "ERR: #{data}"
channel.send_data "INVALID PASSWORD\n"
end
end
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