6

net-sshを使用してrubyでログインシェルを取得する方法はありますか?それも可能ですか?

ログインシェルとは、ソース/ etc/profile。を意味します。

4

2 に答える 2

14

Net-SSHは低レベルであるため、これを前もって提供することはできません(とにかく、現在のように)。ログインシェル機能を追加するためにNet-SSHに基づいて構築されたNet-SSH-Shellをチェックアウトできます:https ://github.com/mitchellh/net-ssh-shell

実装はしっかりしていて機能しますが、コマンドはサブシェルで実行されるため、stderrや終了ステータスなどを具体的に抽出できず、stdoutしか取得できないため、あまり有用ではないことがわかりました。net-ssh-shellライブラリは、いくつかのハックを使用して終了ステータスを取得します。

自分のRubyプロジェクトには「ログインシェル」が必要でした。これを行うには、通常、次のコードを使用してシェルに直接実行しました。

def execute_in_shell!(commands, shell="bash")
  channel = session.open_channel do |ch|
    ch.exec("#{shell} -l") do |ch2, success|
      # Set the terminal type
      ch2.send_data "export TERM=vt100\n"

      # Output each command as if they were entered on the command line
      [commands].flatten.each do |command|
        ch2.send_data "#{command}\n"
      end

      # Remember to exit or we'll hang!
      ch2.send_data "exit\n"

      # Configure to listen to ch2 data so you can grab stdout
    end
  end

  # Wait for everything to complete
  channel.wait
end

このソリューションでは、終了ステータスを取得したり、ログインシェルに実行されたコマンドのstderrを取得したりすることはできませんが、少なくともコマンドはそのコンテキストで実行されます。

これがお役に立てば幸いです。

于 2011-03-17T19:43:34.903 に答える
0

今これを行うためのより良い方法があります。代わりに、ptyでシェルサブシステムを使用して、シェルログインから期待するすべてのものを取得できます。

Net::SSH.start(@config.host, @config.user, :port => @config.port, :keys => @config.key, :config => true) do |session|
  session.open_channel do |channel|
    channel.request_pty
    channel.send_channel_request "shell" do |ch, success|
      if success
        ch.send_data "env\n"
        ch.send_data "#{command}\n"
        ch.on_data do |c, data|
          puts data
        end
      end
      channel.send_data "exit\n"

      channel.on_close do
        puts "shell closed"
      end
    end
  end
end

終わり

于 2018-05-06T14:20:18.080 に答える