aboutsummaryrefslogtreecommitdiff
path: root/doc/commands.dox
blob: 1e52ed4a558c667a15a61c1dfe66bba2e976cdd5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
@page commands Chapter 4: Passing remote commands
@section remote_commands Passing remote commands

Previous chapter has shown how to open a full shell session, with an attached
terminal or not. If you only need to execute commands on the remote end,
you don't need all that complexity.

@subsection exec_remote Executing remote commands

The first steps for executing remote commands are identical to those
for opening remote shells. You first need a SSH channel, and then
a SSH session that uses this channel:

@code
int show_remote_files(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;
  }
@endcode

Once a session is open, you can start the remote command with
ssh_channel_request_exec():

@code
  rc = ssh_channel_request_exec(channel, "ls -l");
  if (rc != SSH_OK)
  {
    ssh_channel_close(channel);
    ssh_channel_free(channel);
    return rc;
  }
@endcode

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:

@code
  char buffer[256];
  unsigned int nbytes;

  nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
  while (nbytes > 0)
  {
    if (write(1, buffer, nbytes) != 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;
  }
@endcode

Once there are no more remote commands to execute, you can send an
end-of-file to the channel, close it, and free the memory it used:

@code
  ssh_channel_send_eof(channel);
  ssh_channel_close(channel);
  ssh_channel_free(channel);

  return SSH_OK;
}
@endcode

*/