public
Created

Test:SSH Connection with socket pair

  • Download Gist
ssh_with_socket.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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
#!/usr/bin/env ruby
$VERBOSE=nil
require 'rubygems'
require 'net/ssh'
require 'logger'
require 'socket'
require 'thread'
 
logger=Logger.new(STDOUT)
s1, s2 = Socket.pair(:UNIX, :STREAM, 0)
 
thread=Thread.new do
Net::SSH.start( 'localhost', `whoami`.chomp) do |session|
session.open_channel do |ch|
logger.info("Channel opened")
ch.exec "bash" do |ch, success|
abort "can't execute!" unless success
logger.info("Bash running")
 
s1.extend(Net::SSH::BufferedIo)
session.listen_to(s1)
logger.info("Socket hooked")
 
ch.on_process do
logger.info("On process")
if s1.available > 0
logger.debug("s1 available")
ch.send_data(s1.read_available)
else
logger.debug("s1 unavailable")
end
end
 
ch.on_close do
logger.info("On close")
session.stop_listening_to(s1)
s1.close
end
end
logger.debug("After exec block")
end
logger.debug("After channel block")
end
logger.debug("After session block")
end
 
logger.info("Before first sleep")
sleep 2
logger.info("Before ls")
s2.print "ls\n"
logger.info("After ls")
sleep 2
logger.info("Before exit")
s2.print "exit\n"
logger.info("After exit")
sleep 2
logger.info("Wait for thread")
thread.join
logger.info("Exit")

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.