ruby net-ssh登录shell

有什么办法可以使用net-ssh在ruby中获取登录shell吗? 这有可能吗?

通过登录shell我的意思是源/ etc / profile ..

Net-SSH的级别太低,无法直接提供(现在的方式,无论如何)。 您可以查看基于Net-SSH构建的Net-SSH-Shell以添加登录shellfunction: https : //github.com/mitchellh/net-ssh-shell

实现是可靠的并且有效,但是我发现它不太有用,因为你不能专门提取诸如stderr或退出状态之类的东西,因为命令在子shell中运行,所以你只能得到stdout。 net-ssh-shell库使用一些hacks来获取退出状态。

我需要一个用于我自己的Ruby项目的“登录shell”,为此我通常使用以下代码将内容直接执行到shell中:

 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命令进入登录shell,但至少命令在该上下文中执行。

我希望这有帮助。

现在有一种更好的方法可以做到这一点。 相反,您可以使用带有pty的shell子系统来获取shell登录所需的所有内容:

 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 

结束