LoginSignup
5
5

More than 5 years have passed since last update.

Rubyでchannel使ってSSHする

Posted at

Rubyでchannel使ってSSHしたいので。メモ。

#coding: utf-8

require 'net/ssh'

Net::SSH.start('host', 'user', :password => 'pass') do |ssh|

  ssh.open_channel do |channel|

    channel.on_data do |ch, data|

      #標準出力
      puts data

    end

    channel.on_extended_data do |ch, type, data|

      #標準エラー
      p data

    end

    channel.send_channel_request "shell" do |ch, success|

      if success

        ch.send_data("ld\n") #標準エラーから出力される
        ch.send_data("ls\n") #標準出力から出力される
        ch.process
        ch.eof!

      else

        p "channel request error"
      end

    end

    channel.on_request "exit-status" do |ch, data|

      #終了ステータス
      p data.read_long

    end

  end

  ssh.loop

end
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5