我正在使用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 :(得分:0)
如果您希望从远程文件中获取异步实时响应,则最好尝试一些特殊的异步I / O API,例如 libevent 。您必须编写自己的客户端和服务器,但这很简单。 您确定需要加密连接吗?如果是,openSSL也受 libevent 支持。
答案 1 :(得分:0)
问题在于我的朋友
nbytes = ssh_channel_read(channel,buffer,sizeof(buffer),0);
最后一个参数是(0)零。如果将其更改为(1)one,则函数将使用Command的结果填充缓冲区。 :D那就是