Ruby和Net :: SSH与交互式命令行应用程序连接

时间:2014-11-27 22:19:04

标签: ruby ssh

我有一个在嵌入式Linux机器上运行的交互式命令行应用程序。启动应用程序后,它接受来自stdin的命令并回复有关stdout和stderr的信息。我通过ssh-terminal与应用程序通信(我在Windows 7机器上使用Tera-Term)。 现在我想用Net :: SSH用ruby应用程序替换ssh-terminal。在PC上运行的ruby应用程序应该向嵌入式Linux应用程序发送命令并回读回复。

为了测试,我编写了以下嵌入式应用程序:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main( int argc, char **argv){
    int i;
    char line[256];
    for (i = 1 ; i < argc ; i++ ){
        printf("arg%d: %s\n", i, argv[i]);
    }

    while(1){
        fgets(line, sizeof(line), stdin);
        printf("You sent: %s", line);
        fflush(stdout);
        if(!strncmp(line,"quit",4)) break;
    }
    printf("Signing off. Good Bye!\n");
    return(0);
}

在PC端,我的ruby脚本如下:

    require 'net/ssh'

HOST='192.168.1.10'
USER='root'
PASS='root'

t0 = Time.now

Net::SSH.start(HOST, USER, :password => PASS) do |ssh|

  channel = ssh.open_channel do |ch|

    ch.exec "/media/card/test2.elf 1 2 3 " do |ch, success|

      raise "could not execute command" unless success

      ch.on_data do |c, data| # handler for remote's stdout
        $stdout.print data
        puts"                 t,receive = #{Time.now-t0} "
      end

      ch.on_extended_data do |c, type, data| # handler for remote's stderr
        $stderr.print data
      end

      ch.on_close do  # handler for remote's exit
        puts "done!"
      end
    end

  end

  t = Thread.new{
    # send data to remote's stdin
    %w(one two three quit).each do |word|
      sleep 0.5
      puts "Sending: #{word}    "
      puts"                 t,send = #{Time.now-t0} "
      channel.send_data word+"\n"
    end
  }  

  ssh.loop(0.05)

end

这是我到目前为止所得到的:

    Sending: one    
                 t,send = 1.954 
arg1: 1
arg2: 2
arg3: 3
You sent: one
                 t,receive = 1.984 
Sending: two    
                 t,send = 2.454 
You sent: two
                 t,receive = 2.494 
Sending: three    
                 t,send = 2.954 
You sent: three
                 t,receive = 3.004 
Sending: quit    
                 t,send = 3.454 
You sent: quit
                 t,receive = 3.514 
Signing off. Good Bye!
                 t,receive = 3.514 
done!

这大部分都有效,但我还没有能解决的一个问题。 我的期望是立即显示远程应用程序的初始输出(以arg1: 1开头的3行)。然而,这种情况并非如此。似乎只有在发送第一个命令后,我才能将所有输出数据提升到You sent: one

如何获得初始输出?

其他信息:

ruby​​ 1.9.3p550(2014-10-27)[i386-mingw32]

net-ssh(2.9.1)

1 个答案:

答案 0 :(得分:0)

放弃了这段时间后,我终于找到了问题。显然只是对我的愚蠢疏忽。问题出在C程序中,我在编写命令行参数后忘记刷新stdout。 这是有效的版本:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main( int argc, char **argv){
    int i;
    char line[256];
    for (i = 1 ; i < argc ; i++ ){
        printf("arg%d: %s\n", i, argv[i]);
    }

    fflush(stdout); // this line added to send command line arguments
    while(1){
        fgets(line, sizeof(line), stdin);
        printf("You sent: %s", line);
        fflush(stdout);
        if(!strncmp(line,"quit",4)) break;
    }
    printf("Signing off. Good Bye!\n");
    return(0);
}