gpt4 book ai didi

c - 使用 ssh 和 libssh2 lib 发送命令

转载 作者:行者123 更新时间:2023-11-30 16:43:50 24 4
gpt4 key购买 nike

我尝试使用 libssh2 通过 ssh 发送命令,但无法收到预期的响应。

它与我的树莓派连接良好。

发送命令的函数:

char * s7c_hardware::sendCmd(char * cmd, bool out)
{
if (!(channel = libssh2_channel_open_session(session))) return "-1";
libssh2_channel_setenv(channel, "FOO", "bar");
if (libssh2_channel_request_pty(channel, "vanilla")) return "-2";
if (libssh2_channel_shell(channel)) return "-3";
int rc;
while ((rc = libssh2_channel_exec(channel, cmd)) ==
LIBSSH2_ERROR_EAGAIN)
{
waitsocket(sock, session);
}
char * output = "";
if (out)
{
do
{
char buffer[99999];
rc = libssh2_channel_read(channel, buffer, sizeof(buffer));
if (rc > 0)
{
fprintf(stderr, "We read:\n");
for (int i = 0; i < rc; ++i)
fputc(buffer[i], stderr);
fprintf(stderr, "\n");
}
else {
if (rc != LIBSSH2_ERROR_EAGAIN)
fprintf(stderr, "libssh2_channel_read returned %d\n", rc);
}
} while (rc > 0);
}
libssh2_channel_free(channel);
channel = NULL;
return output;
}

其中cmd是命令,out是是否想要输出。

如果我尝试发送“正常运行时间”并接收正常运行时间,我会收到以下内容:

We read:

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Sat Jul 1 10:27:51 2017 from desktop-ca160hm.local

We read:
pi@rasp:~$

最佳答案

我认为请求 shell 和请求执行单个命令是相互排斥的。如果您想运行命令、获取其输出并结束 channel (不一定是 session ),您应该运行 libssh2_channel_exec运行 libssh2_channel_shell.

关于c - 使用 ssh 和 libssh2 lib 发送命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44914540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com