使用 libssh 的自定义命令

Custom commands with libssh

本文关键字:命令 自定义 libssh 使用      更新时间:2023-10-16

>我正在使用SSH与秃鹰服务器通信,需要调用自定义控制的命令(即 condor_submitcondor_makecondor_q等)。在我的 Xcode 项目中下载并成功集成 libSSH 后(是的,我使用的是 Mac OS),我发现提供的功能不支持自定义命令。本教程指出,这将在主机上执行命令:


rc = ssh_channel_request_exec(channel, "ls -l");
if (rc != SSH_OK) {
  ssh_channel_close(channel);
  ssh_channel_free(channel);
  return rc;
}

然而,当我用比方说"condor_q"替换"ls -l"时,该命令似乎没有执行。我设法通过使用交互式 shell 会话来解决此问题,如下所示:


// Create channel
rc = ssh_channel_request_pty(channel);
if (rc != SSH_OK) return rc;
rc = ssh_channel_change_pty_size(channel, 84, 20);
if (rc != SSH_OK) return rc;
rc = ssh_channel_request_shell(channel);
std::string commandString = "condor_q";
char buffer[512];
int bytesRead, bytesWrittenToConsole;
std::string string;
while (ssh_channel_is_open(channel) && !ssh_channel_is_eof(channel)) {
    // _nonblocking
    bytesRead = ssh_channel_read_nonblocking(channel, buffer, sizeof(buffer), 0);
    if (bytesRead < 0) {
        rc = SSH_ERROR;
        break;
    }
    if (bytesRead > 0) {
        for (int i = 0; i < bytesRead; i++) {
            string.push_back(buffer[i]);
        }
        bytesWrittenToConsole = write(1, buffer, bytesRead);
        if (string.find("$") != std::string::npos) {
            if (commandString.length() > 0) {
                ssh_channel_write(channel, commandString.c_str(), commandString.length());
                ssh_channel_write(channel, "n", 1);
            } else {
                break;
            }
            commandString.clear();
            string.clear();
        }
    }
}
// Distroy channel

所以我的问题,有没有一种更简单的方法通过SSH发送自定义命令,而不必"伪造发送"命令?

谢谢

麦克斯

自定义命令通常会转储到 stderr 缓冲区中。

因此,如果您使用自定义命令,请尝试使用通道读取,如下所示:

rc = ssh_channel_read(channel, buffer, sizeof(buffer), 1);

请注意最后一个函数属性上的 0 -> 1 更改。此属性告诉读取从通道上的 stderr 读取,其中某些信息可能被转储。

试试吧。

rc = ssh_channel_request_exec(channel, "ls -l");

成功的返回代码告诉您命令已成功发送到服务器,但不会告诉您它已成功执行。您需要等待并检查退出代码或等待输出。

你读过吗:

http://api.libssh.org/stable/libssh_tutor_command.html

并查看源代码中的examples/exec.c?