0

我正在使用 SSH 与 condor 服务器进行通信,并且需要调用命令以进行自定义控制(即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;
}

资源

然而,当我"ls -l"用 let's say替换时"condor_q",命令似乎没有执行。我设法通过使用这样的交互式 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 发送自定义命令,而不必“假发送”命令?

谢谢

最大限度

4

2 回答 2

1

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

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

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

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

试试看。

于 2013-08-22T18:02:40.800 回答
-2

rc = ssh_channel_request_exec(通道,“ls -l”);

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

你读过:

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

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

于 2012-11-12T14:59:26.497 回答