我正在使用 SSH 与 condor 服务器进行通信,并且需要调用命令以进行自定义控制(即condor_submit
、condor_make
、condor_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 发送自定义命令,而不必“假发送”命令?
谢谢
最大限度