From d0647afae50294ec09b3ce7c968c7c6c42f4190d Mon Sep 17 00:00:00 2001 From: Andreas Schneider Date: Tue, 22 Dec 2009 18:33:16 +0100 Subject: Added an example for exec. --- examples/CMakeLists.txt | 2 ++ examples/exec.c | 67 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 examples/exec.c (limited to 'examples') diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 3e7b6dcc..77eb4173 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -14,10 +14,12 @@ include_directories( add_executable(libssh_scp libssh_scp.c ${examples_SRCS}) add_executable(scp_download scp_download.c ${examples_SRCS}) add_executable(samplessh sample.c ${examples_SRCS}) +add_executable(exec exec.c ${examples_SRCS}) target_link_libraries(libssh_scp ${LIBSSH_SHARED_LIBRARY}) target_link_libraries(scp_download ${LIBSSH_SHARED_LIBRARY}) target_link_libraries(samplessh ${LIBSSH_SHARED_LIBRARY}) +target_link_libraries(exec ${LIBSSH_SHARED_LIBRARY}) include_directories( ${LIBSSH_PUBLIC_INCLUDE_DIRS} diff --git a/examples/exec.c b/examples/exec.c new file mode 100644 index 00000000..077b94fd --- /dev/null +++ b/examples/exec.c @@ -0,0 +1,67 @@ +/* simple exec example */ +#include + +#include +#include "examples_common.h" + +int main(void) { + ssh_session session; + ssh_channel channel; + ssh_buffer buf; + int rc; + + session = connect_ssh("localhost", NULL, 0); + if (session == NULL) { + return 1; + } + + channel = channel_new(session);; + if (channel == NULL) { + ssh_disconnect(session); + ssh_finalize(); + return 1; + } + + rc = channel_open_session(channel); + if (rc < 0) { + channel_close(channel); + ssh_disconnect(session); + ssh_finalize(); + return 1; + } + + rc = channel_request_exec(channel, "ps aux"); + if (rc < 0) { + channel_close(channel); + ssh_disconnect(session); + ssh_finalize(); + return 1; + } + + + if (channel_is_open(channel)) { + while (channel_poll(channel, 0) >= 0) { + buf = buffer_new(); + rc = channel_read_buffer(channel, buf, 0, 0); + if (rc < 0) { + buffer_free(buf); + channel_close(channel); + ssh_disconnect(session); + ssh_finalize(); + return 1; + } + + printf("%s\n", (char *) buffer_get(buf)); + + buffer_free(buf); + } + } + + channel_send_eof(channel); + channel_close(channel); + + ssh_disconnect(session); + ssh_finalize(); + + return 0; +} -- cgit v1.2.3