Passing a remote command
Previous chapter has shown how to open a full shell session, with an attached terminal or not. If you only need to execute a command on the remote end, you don't need all that complexity.
The method described here is suited for executing only one remote command. If you need to issue several commands in a row, you should consider using a non-interactive remote shell, as explained in previous chapter.
- See also
- shell
Executing a remote command
The first steps for executing a remote command are identical to those for opening remote shells. You first need a SSH channel, and then a SSH session that uses this channel:
int show_remote_files(ssh_session session)
{
ssh_channel channel;
int rc;
if (channel == NULL) return SSH_ERROR;
if (rc != SSH_OK)
{
return rc;
}
LIBSSH_API void ssh_channel_free(ssh_channel channel)
Close and free a channel.
Definition channels.c:1258
LIBSSH_API ssh_channel ssh_channel_new(ssh_session session)
Allocate a new channel.
Definition channels.c:90
LIBSSH_API int ssh_channel_open_session(ssh_channel channel)
Open a session channel (suited for a shell, not TCP forwarding).
Definition channels.c:1052
Once a session is open, you can start the remote command with ssh_channel_request_exec():
if (rc != SSH_OK)
{
return rc;
}
LIBSSH_API int ssh_channel_close(ssh_channel channel)
Close a channel.
Definition channels.c:1421
LIBSSH_API int ssh_channel_request_exec(ssh_channel channel, const char *cmd)
Run a shell command without an interactive shell.
Definition channels.c:2789
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;
while (nbytes > 0)
{
if (fwrite(buffer, 1, nbytes, stdout) != nbytes)
{
return SSH_ERROR;
}
}
if (nbytes < 0)
{
return SSH_ERROR;
}
LIBSSH_API int ssh_channel_read(ssh_channel channel, void *dest, uint32_t count, int is_stderr)
Reads data from a channel.
Definition channels.c:3051
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:
return SSH_OK;
}
LIBSSH_API int ssh_channel_send_eof(ssh_channel channel)
Send an end of file on the channel.
Definition channels.c:1360