function execcmd()

void execcmd(const char *commandline, int sock, LIBSSH2_SESSION *session)
{
    int rc;
    int bytecount = 0;
    int exitcode;
    char *exitsignal=(char *)"none";
    LIBSSH2_CHANNEL *channel = NULL;
   
    while( (channel = libssh2_channel_open_session(session)) == NULL &&
       libssh2_session_last_error(session,NULL,NULL,0) ==
       LIBSSH2_ERROR_EAGAIN )
    {
        waitsocket(sock, session);
    }
   
    if( channel == NULL )
    {
        fprintf(stderr,"Error\n");
        exit( 1 );
    }
   
    while( (rc = libssh2_channel_exec(channel, commandline)) ==
           LIBSSH2_ERROR_EAGAIN )
    {
        waitsocket(sock, session);
    }
   
    if( rc != 0 )
    {
        fprintf(stderr,"Error: %i\n", rc);
        exit( 1 );
    }

    for( ;; )
    {
        /* loop until we block */
        int rc;
        do
        {
            char buffer[0x4000];
            rc = libssh2_channel_read( channel, buffer, sizeof(buffer) );

            if ( rc > 0 )
            {
                int i;
                bytecount += rc;
                fprintf(stderr, "We read:\n");
                for( i=0; i < rc; ++i )
                    fputc( buffer[i], stderr);
                fprintf(stderr, "\n");
            }
            else
            {
                if ( rc != LIBSSH2_ERROR_EAGAIN )
                {
                    /* no need to output this for the EAGAIN case */
                    fprintf(stderr, "libssh2_channel_read returned %d\n", rc);
                }
            }
        }
        while( rc > 0 );

        /* this is due to blocking that would occur otherwise so we loop on
           this condition */
        if ( rc == LIBSSH2_ERROR_EAGAIN )
            waitsocket(sock, session);
        else
            break;
    }

    exitcode = 127;
   
    while( (rc = libssh2_channel_close(channel)) == LIBSSH2_ERROR_EAGAIN )
        waitsocket(sock, session);

    if( rc == 0 )
    {
        exitcode = libssh2_channel_get_exit_status( channel );
        libssh2_channel_get_exit_signal(channel, &exitsignal,
                                        NULL, NULL, NULL, NULL, NULL);
    }

    if (exitsignal)
        printf("\nGot signal: %s\n", exitsignal);
    else
        printf("\nEXIT: %d bytecount: %d\n", exitcode, bytecount);

    libssh2_channel_free(channel);
    channel = NULL;
}

No comments: