当我尝试在服务器(路由器)上运行命令时,我得到了
大部分代码来自文档。
有代码:
#include <iostream>
#include <string.h>
#include <libssh/libssh.h>
using std::string;
using std::cout;
using std::endl;
using std::cin;
string exec_ssh_command(ssh_session
session, char *command) {
string receive = "";
int rc, nbytes;
char buffer[256];
ssh_channel channel = ssh_channel_new(session);
if( channel == NULL )
return NULL;
rc = ssh_channel_open_session(channel);
if( rc != SSH_OK ) {
ssh_channel_free(channel);
return NULL;
}
rc = ssh_channel_request_exec(channel, command);
if( rc != SSH_OK ) {
ssh_channel_close(channel);
ssh_channel_free(channel);
cout << "Error";
return NULL;
}
nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
while (nbytes > 0)
{
if (write(1, buffer, nbytes) != (unsigned int) nbytes)
{
ssh_channel_close(channel);
ssh_channel_free(channel);
return NULL;
}
nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
}
if( nbytes < 0 )
return NULL;
ssh_channel_send_eof(channel);
ssh_channel_close(channel);
ssh_channel_free(channel);
return receive;
}
int main() {
ssh_session my_ssh_session = ssh_new();
if( my_ssh_session == NULL ) {
cout << "Error creating ssh session" << endl;
return 1;
}
ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "192.168.1.1");
ssh_options_set(my_ssh_session, SSH_OPTIONS_USER, "admin");
int rc = ssh_connect(my_ssh_session);
if( rc != SSH_OK ) {
cout << "Error with connecting" << endl;
ssh_free(my_ssh_session);
return -1;
}
rc = ssh_userauth_password(my_ssh_session, NULL, "pass");
if( rc != SSH_AUTH_SUCCESS) {
cout << "Error with authorization " << ssh_get_error(my_ssh_session) << endl;
ssh_disconnect(my_ssh_session);
ssh_free(my_ssh_session);
return -1;
}
string ip_hotspot = exec_ssh_command(my_ssh_session, "show ip hotspot");
cout << ip_hotspot << endl;
ssh_disconnect(my_ssh_session);
ssh_free(my_ssh_session);
return 0;
}
我的路由器是zyxel keenetic ultra。
别名-a:
Linux localhost 4.9.112-perf-gfb7749d #1 SMP PREEMPT Thu Dec 6 16:06:30 WIB 2018 aarch64 Android
g++ -v:
clang version 7.0.1 (tags/RELEASE_701/final)Target: aarch64--linux-androidThread model: posix
我是libssh的初学者,所以请简单说明。 :)
先感谢您!
最佳答案
它是固定的。在3.3.2
的Keenetic OS
版本上,它可以正常工作。
关于c++ - 尝试在路由器上执行命令。 C++和libssh,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54015841/