require 'net/ssh'
host = "the.host"
user = "joe"
su_user = "bob"
password = "password"
commands = ["cd /", "pwd", "ls -l", "exit"]
finished = ("%08x" * 8) % Array.new(8) { rand(0xFFFFFFFF) }
Net::SSH.start(host, user) do |ssh|
  ssh.open_channel do |channel|
    channel.request_pty(:modes => { Net::SSH::Connection::Term::ECHO => 0 }) do |c, success|
      raise "could not request pty" unless success
      channel.on_data do |c_, data|
        if data =~ /^Password:/
          channel.send_data(password + "\n")
          channel.send_data(commands.shift + "; echo #{finished}\n")
        elsif data.include?(finished)
          channel.send_data(commands.shift + "; echo #{finished}\n")
        else
          puts data
        end
      end
      channel.exec "su #{su_user}"
    end
  end
  ssh.loop
end