我尝试使用在libssh示例中建立的部分代码来制作ssh远程命令,并尝试在执行函数之外输出这样的输出
在int main();
printf("Server output: %s", nbytes);
int exec_uname(ssh_session session) {
ssh_channel channel;
int rc;
channel = ssh_channel_new(session);
if (channel == NULL) return SSH_ERROR;
rc = ssh_channel_open_session(channel);
if (rc != SSH_OK) {
ssh_channel_free(channel);
return rc;
}
//Once a session is open, you can start the remote command with ssh_channel_request_exec():
rc = ssh_channel_request_exec(channel, "uname -a");
if (rc != SSH_OK) {
ssh_channel_close(channel);
ssh_channel_free(channel);
return rc;
}
//If the remote command displays data, you get them with ssh_channel_read(). This function returns the number of bytes read. If there is no more data to read on the channel, this function returns 0, and you can go to next step. If an error has been encountered, it returns a negative value:
char buffer[256];
int nbytes;
nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
while (nbytes > 0) {
if (fwrite(buffer, 1, nbytes, stdout) != nbytes) {
ssh_channel_close(channel);
ssh_channel_free(channel);
return SSH_ERROR;
}
nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
}
if (nbytes < 0) {
ssh_channel_close(channel);
ssh_channel_free(channel);
return SSH_ERROR;
}
//Once you read the result of the remote command, you send an end-of-file to the channel, close it, and free the memory that it used:
ssh_channel_send_eof(channel);
ssh_channel_close(channel);
ssh_channel_free(channel);
return SSH_OK;
}
答案 0 :(得分:1)
您不能在函数外部访问局部变量。您可以在更广泛的范围内声明它,例如global,这是最后的手段,或者将其传递以填充。
例如:
Error: ENOENT: no such file or directory, open 'Risk Category,Risk ID,Risk Value
Some,Some,Some
Some,Some,Some
Some,Some,Some'
at Object.openSync (fs.js:436:3)
at Object.readFileSync (fs.js:341:35)
at router.post (C:\client_projects\tt\sarcs-hotline\router\index.js:1039:21)
at Layer.handle [as handle_request] (C:\client_projects\tt\sarcs-hotline\node_modules\express\lib\router\layer.js:95:5)
at next (C:\client_projects\tt\sarcs-hotline\node_modules\express\lib\router\route.js:137:13)
at Array.<anonymous> (C:\client_projects\tt\sarcs-hotline\node_modules\multer\lib\make-middleware.js:53:37)
at listener (C:\client_projects\tt\sarcs-hotline\node_modules\on-finished\index.js:169:15)
at onFinish (C:\client_projects\tt\sarcs-hotline\node_modules\on-finished\index.js:100:5)
at callback (C:\client_projects\tt\sarcs-hotline\node_modules\ee-first\index.js:55:10)
at IncomingMessage.onevent (C:\client_projects\tt\sarcs-hotline\node_modules\ee-first\index.js:93:5)
at IncomingMessage.emit (events.js:182:13)
at endReadableNT (_stream_readable.js:1094:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
因此,当被调用时:
int exec_uname(ssh_session session, int* bytes) {
// ... code
// Push back to caller
*bytes = nbytes;
}
您仍然需要检查int nbytes;
int result = exec_uname(session, &nbytes);
printf("Server output: %d", nbytes);
,以确保函数正确终止,否则result
中的值将不可用。