0

我正在使用 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;




}
}
4

2 回答 2

0

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

于 2013-09-10T10:27:15.400 回答
0

问题出在这条线上,我的朋友

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

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

于 2014-09-27T09:08:57.783 回答