secret
anonymous / ssh_example.rb
Created

Interactive SSH Example w/ multiple channels

  • Download Gist
ssh_example.rb
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 25 26 27 28 29 30 31 32 33 34
$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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.