2012-01-03 86 views
0

我正在使用libssh将远程命令发送到计算机。这个命令是实时的,所以我试图在数据包生成时获取它。基本上我是十六进制的鼠标事件,我想要这些数据。如何使我的命令返回实时结果?libssh不返回命令结果

#include <libssh/libssh.h> 

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



/* 
* 1) Set ssh options 
* 2) Connect 
* 3) Authenticate 
* 4) Set channels 
* 5) Execute command 
* */ 


int main() 
{ 

    //Initilization 
    ssh_session session; 
    int verbosity = SSH_LOG_PROTOCOL; 
    int port = 22; 

    char* password ="root"; 
    int rc; 


    session = ssh_new(); 
    if (session == NULL) 
     return(-1); 

    //Set options for SSH connection 
    ssh_options_set(session,SSH_OPTIONS_HOST,"90.12.34.44"); 
    ssh_options_set(session,SSH_OPTIONS_LOG_VERBOSITY,&verbosity); 
    ssh_options_set(session,SSH_OPTIONS_PORT,&port); 

    ssh_options_set(session,SSH_OPTIONS_USER,"root"); 



    //Connect to server 

    rc = ssh_connect(session); 
    if (rc != SSH_OK) 
    { 
     fprintf(stderr,"Error connecting to host %s\n",ssh_get_error(session)); 
    ssh_free(session); 
    return(-1); 
    } 



    rc = ssh_userauth_password(session,NULL,password); 
    if (rc == SSH_AUTH_SUCCESS) 
    { 
     printf("Authenticated correctly"); 

    } 


    ssh_channel channel; 
    channel = ssh_channel_new(session); 
    if(channel == NULL) return SSH_ERROR; 

    rc = ssh_channel_open_session(channel); 
    if (rc != SSH_OK) 
    { 
     ssh_channel_free(channel); 
     return rc; 
    } 


    rc = ssh_channel_request_exec(channel,"hd /dev/input/event0"); 
    if (rc != SSH_OK) 
    { 
     ssh_channel_close(channel); 
     ssh_channel_free(channel); 
     return rc; 
    } 



    char buffer[30]; 
    unsigned int nbytes; 

    nbytes = ssh_channel_read(channel,buffer,sizeof(buffer),0); 
    while(nbytes > 0) 
    { 
     if(fwrite(buffer,1,nbytes,stdout)); 
     { 
      ssh_channel_close(channel); 
     ssh_channel_free(channel); 
     return SSH_ERROR; 

     } 

     nbytes = ssh_channel_read(channel,buffer,sizeof(buffer),0); 


    if (nbytes < 0) 
    { 

     ssh_channel_close(channel); 
    ssh_channel_free(channel); 
    return SSH_ERROR; 
    } 

    return 0; 




} 
} 
+0

那么你的问题是什么? – 2012-01-03 07:18:44

+2

你知道'fwrite'返回写入的“items”的数量,所以写入'stdout'的成功写入将作为代码中的错误处理。 – 2012-01-03 07:31:24

回答

0

如果要被改变从远程文件获取异步实时响应,你最好尝试一些特别的异步I/O API,像的libevent。你将不得不编写你自己的客户端和服务器,但它很简单。 您确定需要加密连接吗?如果你是,openSSL也支持libevent

0

的问题是在这条线我的朋友

nbytes = ssh_channel_read(channel,buffer,sizeof(buffer),0); 

最后一个参数为(0)零。如果将其更改为(1),函数将使用命令的结果填充缓冲区。 :D就是这样

相关问题