I am using ssh_channel_request_exec
to execute a command mkdir -p ~/.temp
on a remote node. When ssh_channel_request_exec
is used along with ssh_channel_read
, the creation of directory is working fine. On the other hand, when ssh_channel_read
is not used, the directory creation is failing.
In this case, ssh_channel_request_exec
is not going to write anything to the channel. So, what is the relevance of ssh_channel_read
here?
int exec_result = ssh_channel_request_exec(channel, "mkdir -p ~/.temp");
if (exec_result != SSH_OK)
{
ssh_channel_close(channel);
ssh_channel_free(channel);
ssh_disconnect(session);
ssh_free(session);
}
You need to allow the command to complete, before closing the channel.
The side effect of the ssh_channel_read
is that it delays closing the channel, until after your command completes. Possibly not always – so you might just have been lucky so far that it delayed closing long enough – longer running commands than mkdir
might still fail.
If you do not want to read the output, you should be able to use ssh_channel_get_exit_status
to determine if the command completed.
I do not know sshlib API enough, but in general with SSH, you need to read the output anyway. Because if you do not, and the command produces enough output to fill the output buffer, the command will hang. See these questions about different SSH APIs:
Side note: For file system operations, you should better use a standard SSH file system API, the SFTP, instead of running shell commands. For sshlib that would be sftp_mkdir
.