Skip to content

Instantly share code, notes, and snippets.

/ssh_example.rb Secret

Created June 29, 2012 15:10
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 anonymous/bf57020feb930f47133e to your computer and use it in GitHub Desktop.
Save anonymous/bf57020feb930f47133e to your computer and use it in GitHub Desktop.
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