コード例 #1
2
ファイル: SSH2Utils.cpp プロジェクト: tasosbull/yewtic
int SSH2Utils::exec(const char *cmd) {
	m_execResultStr.clear();
	int rc = -1;
	LIBSSH2_CHANNEL *channel;
	/* Exec non-blocking on the remove host */
	while ((channel = libssh2_channel_open_session(m_session)) == NULL
			&& libssh2_session_last_error(m_session, NULL, NULL, 0)
					== LIBSSH2_ERROR_EAGAIN) {
		waitsocket();
	}
	if (channel == NULL) {
		fprintf(stderr, "Channel Error\n");
		m_errCode = 9;
		return -1;
	}

    /* Request a terminal with 'vanilla' terminal emulation
     * See /etc/termcap for more options
     */
    if (libssh2_channel_request_pty(channel, "vanilla")) {
        fprintf(stderr, "Failed requesting pty\n");
    }

    /* Open a SHELL on that pty */
    if (libssh2_channel_shell(channel)) {
        fprintf(stderr, "Unable to request shell on allocated pty\n");
    }

    libssh2_channel_write(channel, cmd, strlen(cmd));
    libssh2_channel_send_eof(channel);
	char buffer[BUF_SIZE];
	memset(buffer, 0, BUF_SIZE);
	rc = libssh2_channel_read(channel, buffer, BUF_SIZE);
	if (rc > 0) {
		m_execResultStr.append(buffer);
	}

	m_channelExitCode = 127;
	while ((rc = libssh2_channel_close(channel)) == LIBSSH2_ERROR_EAGAIN)
		waitsocket();
	if (rc == 0) {
		m_channelExitCode = libssh2_channel_get_exit_status(channel);
	}

skip_shell:
	if (channel) {
		libssh2_channel_free(channel);
		channel = NULL;
	}
	return rc;
}
コード例 #2
1
ファイル: ssh2_exec.c プロジェクト: karelia/libssh2
int main(int argc, char *argv[])
{
    const char *hostname = "127.0.0.1";
    const char *commandline = "uptime";
    const char *username    = "******";
    const char *password    = "******";
    unsigned long hostaddr;
    int sock;
    struct sockaddr_in sin;
    const char *fingerprint;
    LIBSSH2_SESSION *session;
    LIBSSH2_CHANNEL *channel;
    int rc;
    int exitcode;
    char *exitsignal=(char *)"none";
    int bytecount = 0;
    size_t len;
    LIBSSH2_KNOWNHOSTS *nh;
    int type;

#ifdef WIN32
    WSADATA wsadata;
    int err;

    err = WSAStartup(MAKEWORD(2,0), &wsadata);
    if (err != 0) {
        fprintf(stderr, "WSAStartup failed with error: %d\n", err);
        return 1;
    }
#endif

    if (argc > 1)
        /* must be ip address only */
        hostname = argv[1];

    if (argc > 2) {
        username = argv[2];
    }
    if (argc > 3) {
        password = argv[3];
    }
    if (argc > 4) {
        commandline = argv[4];
    }

    rc = libssh2_init (0);
    if (rc != 0) {
        fprintf (stderr, "libssh2 initialization failed (%d)\n", rc);
        return 1;
    }

    hostaddr = inet_addr(hostname);

    /* Ultra basic "connect to port 22 on localhost"
     * Your code is responsible for creating the socket establishing the
     * connection
     */
    sock = socket(AF_INET, SOCK_STREAM, 0);

    sin.sin_family = AF_INET;
    sin.sin_port = htons(22);
    sin.sin_addr.s_addr = hostaddr;
    if (connect(sock, (struct sockaddr*)(&sin),
                sizeof(struct sockaddr_in)) != 0) {
        fprintf(stderr, "failed to connect!\n");
        return -1;
    }

    /* Create a session instance */
    session = libssh2_session_init();
    if (!session)
        return -1;

    /* tell libssh2 we want it all done non-blocking */
    libssh2_session_set_blocking(session, 0);

    /* ... start it up. This will trade welcome banners, exchange keys,
     * and setup crypto, compression, and MAC layers
     */
    while ((rc = libssh2_session_handshake(session, sock)) ==
            LIBSSH2_ERROR_EAGAIN);
    if (rc) {
        fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
        return -1;
    }

    nh = libssh2_knownhost_init(session);
    if(!nh) {
        /* eeek, do cleanup here */
        return 2;
    }

    /* read all hosts from here */
    libssh2_knownhost_readfile(nh, "known_hosts",
                               LIBSSH2_KNOWNHOST_FILE_OPENSSH);

    /* store all known hosts to here */
    libssh2_knownhost_writefile(nh, "dumpfile",
                                LIBSSH2_KNOWNHOST_FILE_OPENSSH);

    fingerprint = libssh2_session_hostkey(session, &len, &type);
    if(fingerprint) {
        struct libssh2_knownhost *host;
#if LIBSSH2_VERSION_NUM >= 0x010206
        /* introduced in 1.2.6 */
        int check = libssh2_knownhost_checkp(nh, hostname, 22,
                                             fingerprint, len,
                                             LIBSSH2_KNOWNHOST_TYPE_PLAIN|
                                             LIBSSH2_KNOWNHOST_KEYENC_RAW,
                                             &host);
#else
        /* 1.2.5 or older */
        int check = libssh2_knownhost_check(nh, hostname,
                                            fingerprint, len,
                                            LIBSSH2_KNOWNHOST_TYPE_PLAIN|
                                            LIBSSH2_KNOWNHOST_KEYENC_RAW,
                                            &host);
#endif
        fprintf(stderr, "Host check: %d, key: %s\n", check,
                (check <= LIBSSH2_KNOWNHOST_CHECK_MISMATCH)?
                host->key:"<none>");

        /*****
         * At this point, we could verify that 'check' tells us the key is
         * fine or bail out.
         *****/
    }
    else {
        /* eeek, do cleanup here */
        return 3;
    }
    libssh2_knownhost_free(nh);

    if ( strlen(password) != 0 ) {
        /* We could authenticate via password */
        while ((rc = libssh2_userauth_password(session, username, password)) ==
                LIBSSH2_ERROR_EAGAIN);
        if (rc) {
            fprintf(stderr, "Authentication by password failed.\n");
            goto shutdown;
        }
    }
    else {
        /* Or by public key */
        while ((rc = libssh2_userauth_publickey_fromfile(session, username,
                     "/home/user/"
                     ".ssh/id_rsa.pub",
                     "/home/user/"
                     ".ssh/id_rsa",
                     password)) ==
                LIBSSH2_ERROR_EAGAIN);
        if (rc) {
            fprintf(stderr, "\tAuthentication by public key failed\n");
            goto shutdown;
        }
    }

#if 0
    libssh2_trace(session, ~0 );
#endif

    /* Exec non-blocking on the remove host */
    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\n");
        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)
        fprintf(stderr, "\nGot signal: %s\n", exitsignal);
    else
        fprintf(stderr, "\nEXIT: %d bytecount: %d\n", exitcode, bytecount);

    libssh2_channel_free(channel);
    channel = NULL;

shutdown:

    libssh2_session_disconnect(session,
                               "Normal Shutdown, Thank you for playing");
    libssh2_session_free(session);

#ifdef WIN32
    closesocket(sock);
#else
    close(sock);
#endif
    fprintf(stderr, "all done\n");

    libssh2_exit();

    return 0;
}
コード例 #3
0
ファイル: publickey.c プロジェクト: Zarzuelo/pandorafms
/* {{{ libssh2_publickey_packet_receive
 * Read a packet from the subsystem
 */
static int libssh2_publickey_packet_receive(LIBSSH2_PUBLICKEY *pkey, unsigned char **data, unsigned long *data_len)
{
	LIBSSH2_CHANNEL *channel = pkey->channel;
	LIBSSH2_SESSION *session = channel->session;
	unsigned char buffer[4];
	unsigned long packet_len;
	unsigned char *packet;

	if (libssh2_channel_read(channel, buffer, 4) != 4) {
		libssh2_error(session, LIBSSH2_ERROR_PUBLICKEY_PROTOCOL, "Invalid response from publickey subsystem", 0);
		return -1;
	}

	packet_len = libssh2_ntohu32(buffer);
	packet = LIBSSH2_ALLOC(session, packet_len);
	if (!packet) {
		libssh2_error(session, LIBSSH2_ERROR_ALLOC, "Unable to allocate publickey response buffer", 0);
		return -1;
	}

	if (libssh2_channel_read(channel, packet, packet_len) != packet_len) {
		libssh2_error(session, LIBSSH2_ERROR_SOCKET_TIMEOUT, "Timeout waiting for publickey subsystem response packet", 0);
		LIBSSH2_FREE(session, packet);
		return -1;
	}

	*data = packet;
	*data_len = packet_len;

	return 0;
}
コード例 #4
0
ファイル: ssh2.cpp プロジェクト: mitchellsimoens/SilkJS
	bool RunCommand(const char *aCommand) {
		if (!mSessionOK) {
			return false;
		}
		LIBSSH2_CHANNEL *channel = libssh2_channel_open_session(mSession);
		if (channel == NULL) {
			strcpy(mErrorMessage, "Could not open SSH2 channel");
			return false;
		}
#ifdef libssh2_session_set_timeout
		libssh2_session_set_timeout(mTimeout);
#endif
		if (libssh2_channel_exec(channel, aCommand) == -1) {
			strcpy(mErrorMessage, "Could not execute SSH2 command");
			return false;
		}
		std::string response;
		char buf[1025];
		ssize_t size = 1024;
		while (size == 1024) {
			size = libssh2_channel_read(channel, buf, 1024);
			buf[size] = '\0';
			response += buf;
		}
		if (mResponse) {
			delete [] mResponse;
		}
		mResponse = new char[response.size()+1];
		strcpy(mResponse, response.c_str());
		libssh2_channel_close(channel);
		mExitCode = libssh2_channel_get_exit_status(channel);
		libssh2_channel_free(channel);
		return true;
	}
コード例 #5
0
ファイル: hiredis.c プロジェクト: TakedWind/fastoredis
int redisReadToBuffer(redisContext *c, char* buf, int size, ssize_t *nread)
{
    *nread = -1;
    /* Return early when the context has seen an error. */
    if (c->err){
        return REDIS_ERR;
    }

    if(c->channel){
        *nread = libssh2_channel_read(c->channel, buf, size);
    }
    else{
        #ifdef OS_WIN
            *nread = recv(c->fd,buf,size,0);
        #else
            *nread = read(c->fd, buf, size);
        #endif
    }

    if (*nread == -1) {
        if ((errno == EAGAIN && !(c->flags & REDIS_BLOCK)) || (errno == F_EINTR)) {
            *nread = 0;
        } else {
            return REDIS_ERR;
        }
    }

    return REDIS_OK;
}
コード例 #6
0
ファイル: hiredis.c プロジェクト: TakedWind/fastoredis
/* Use this function to handle a read event on the descriptor. It will try
 * and read some bytes from the socket and feed them to the reply parser.
 *
 * After this function is called, you may use redisContextReadReply to
 * see if there is a reply available. */
int redisBufferRead(redisContext *c) {
    char buf[1024*16];
    int nread;

    /* Return early when the context has seen an error. */
    if (c->err)
        return REDIS_ERR;

#ifdef FASTOREDIS

    if(c->channel){
        nread = libssh2_channel_read(c->channel, buf, sizeof(buf));
    }
    else{
        #ifdef OS_WIN
            nread = recv(c->fd,buf,sizeof(buf),0);
        #else
            nread = read(c->fd,buf,sizeof(buf));
        #endif
    }

    if (nread == -1) {
        if ((errno == EAGAIN && !(c->flags & REDIS_BLOCK)) || (errno == F_EINTR)) {
            /* Try again later */
        } else {
            __redisSetError(c,REDIS_ERR_IO,NULL);
            return REDIS_ERR;
        }
    } else if (nread == 0) {
        __redisSetError(c,REDIS_ERR_EOF,"Server closed the connection");
        return REDIS_ERR;
    } else {
        if (redisReaderFeed(c->reader,buf,nread) != REDIS_OK) {
            __redisSetError(c,c->reader->err,c->reader->errstr);
            return REDIS_ERR;
        }
    }
#else
    nread = read(c->fd,buf,sizeof(buf));
    if (nread == -1) {
        if ((errno == EAGAIN && !(c->flags & REDIS_BLOCK)) || (errno == EINTR)) {
            /* Try again later */
        } else {
            __redisSetError(c,REDIS_ERR_IO,NULL);
            return REDIS_ERR;
        }
    } else if (nread == 0) {
        __redisSetError(c,REDIS_ERR_EOF,"Server closed the connection");
        return REDIS_ERR;
    } else {
        if (redisReaderFeed(c->reader,buf,nread) != REDIS_OK) {
            __redisSetError(c,c->reader->err,c->reader->errstr);
            return REDIS_ERR;
        }
    }
#endif
    return REDIS_OK;
}
コード例 #7
0
/*
 * If the read would block (EWOULDBLOCK) we return -1. Otherwise we return
 * a regular CURLcode value.
 */
ssize_t Curl_scp_recv(struct connectdata *conn, int sockindex,
                  char *mem, size_t len)
{
  ssize_t nread;

  /* libssh2_channel_read() returns int
   *
   * NOTE: we should not store nor rely on connection-related data to be
   * in the SessionHandle struct
   */

  nread = (ssize_t)
    libssh2_channel_read(conn->data->reqdata.proto.ssh->ssh_channel,
                         mem, len);
  (void)sockindex;
  return nread;
}
コード例 #8
0
ファイル: ssh.c プロジェクト: davidreynolds/rtop
static int read_channel(LIBSSH2_CHANNEL *channel, LIBSSH2_SESSION *session,
                        int sock, char **buf)
{
    size_t size = 0x4000, bytes = 0;
    char *pbuf;

    pbuf = malloc(size);

    while (1) {
        int ret;
        char rbuf[0x4000];

        do {
            memset(rbuf, 0, sizeof rbuf);
            ret = libssh2_channel_read(channel, rbuf, sizeof(rbuf));
            if (ret > 0) {
                int len = snprintf(pbuf+bytes, ret, "%s", rbuf);
                if (bytes+len > size) {
                    char *newbuf = realloc(pbuf, size*2);
                    if (!newbuf) {
                        free(pbuf);
                        return -1;
                    }

                    size *= 2;
                    pbuf = newbuf;
                    len = snprintf(pbuf+bytes, ret, "%s", rbuf);
                }

                bytes += len;
            }
        } while (ret > 0);

        if (ret == LIBSSH2_ERROR_EAGAIN) {
            /* read again in a few seconds */
            waitsocket(session, sock);
        } else {
            /* TODO: check if ret < 0 because it's an error */
            break;
        }
    }

    *buf = pbuf;
    return bytes;
}
コード例 #9
0
ファイル: main.c プロジェクト: dgoulet/debind
/*
 * Get DNS query using SSH transport layer.
 */
static ssize_t dig_ssh_request(struct ssh_session *ssh_info,
		char *buf, size_t buf_size, ssize_t len)
{
	int ret;
	ssize_t recv_size;

	do {
		ret = libssh2_channel_write(ssh_info->channel, buf, len);
		if (ret < 0) {
			ERR("libssh2_channel_write: %d", ret);
			goto error;
		}
		DBG("DNS request of size %ld sent to ssh channel", len);

		recv_size = libssh2_channel_read(ssh_info->channel, buf, buf_size);
		if (recv_size < 0) {
			char *buf;
			ERR("SSH channel read failed");
			libssh2_session_last_error(ssh_info->session, &buf, NULL, 0);
			ERR("Failure: %s", buf);
		} else if (recv_size == 0) {
			ret = libssh2_channel_eof(ssh_info->channel);
			if (ret) {
				DBG("SSH server disconnected!");
				libssh2_channel_close(ssh_info->channel);
				libssh2_channel_free(ssh_info->channel);
				/* Create new channel */
				ret = ssh_setup_tunnel(ssh_info, dns_ip);
				if (ret < 0) {
					goto error;
				}
			}
		} else {
			DBG("DNS reply red from ssh channel (size: %ld)",
					recv_size);
			goto end;
		}
	} while (1);

end:
	return recv_size;

error:
	return -1;
}
コード例 #10
0
void* shell_channel_read_write_thread(void* arg)
{
    SSH_SESSION* p_session = (SSH_SESSION*)arg;
    COMMAND_LIST* p_data;
    int rc;
    char* buffer;
    int buffer_length = COMMAND_RESULT_BUFFER_LENGTH;
    buffer = (char*)malloc(sizeof(char) * buffer_length + 1);
    //usleep(50000);
    while(!(ori_thread_is_cancelled(p_session->thread_param->exec_command_thread)))
    {
        //read
        memset(buffer, 0, buffer_length + 1);
        rc = libssh2_channel_read(p_session->session_param->channel, buffer, buffer_length);
        if(rc > 0){
            p_session->callback(buffer, NULL, p_session->obj);
        }
        else
        {
            usleep(100000);
        }
        
        //write
        p_data = (COMMAND_LIST*)malloc(sizeof(COMMAND_LIST));
        rc = safety_queue_pop_front(p_session->thread_param->command_queue_mutex, p_session->command_queue, p_data);
        if(rc == 0)
        {
            libssh2_channel_write(p_session->session_param->channel, p_data->command, strlen(p_data->command));
            free(p_data->command);
        }
        free(p_data);
    }
    
    free(buffer);
    
    if(p_session->thread_param->command_timer_thread_flag)
    {
        ori_thread_cancel(p_session->thread_param->command_timer_thread);
        ori_thread_join(p_session->thread_param->command_timer_thread);
        ori_thread_free(p_session->thread_param->command_timer_thread);
        p_session->thread_param->command_timer_thread = NULL;
    }
    p_session->thread_param->exec_command_thread_flag = FALSE;
    return NULL;
}
コード例 #11
0
ファイル: xferchannel.cpp プロジェクト: PonyEdit/PonyEdit
ShellChannel::ReadReply XferChannel::readBinaryData( int size ) {
	ReadReply reply;
	reply.readAgain = false;

	if ( size <= 0 ) {
		return reply;
	}

	while ( mBinaryReadBuffer.length() < size ) {
		// Flush anything from the read buffer into the binary buffer
		int transferred = Tools::unbin( mBinaryReadBuffer,
		                                mReadBuffer,
		                                size,
		                                mReadBuffer.length(),
		                                &mLeftoverEscape );
		mReadBuffer = mReadBuffer.right( mReadBuffer.size() - transferred );

		if ( mBinaryReadBuffer.length() == size ) {
			break;
		}

		// See if there's data waiting to be read, push it into the read buffer (raw)
		int rc = libssh2_channel_read( mHandle, mScratchBuffer, SSH_SHELL_BUFFER_SIZE );
		if ( rc > 0 ) {
			mReadBuffer.append( mScratchBuffer, rc );
		} else if ( rc == LIBSSH2_ERROR_EAGAIN ||
		            ( rc == -1 &&
		              libssh2_session_last_errno( mSession->sessionHandle() ) == LIBSSH2_ERROR_EAGAIN ) ) {
			reply.readAgain = true;
			return reply;
		} else {
			criticalError( "Connection closed unexpectedly!" );
		}

		int currentLength = mBinaryReadBuffer.length();
		int percent = ( int ) ( ( ( float ) currentLength / size ) * 100 );
		mCurrentRequest->handleProgress( percent );
	}

	// If it reaches here, enough data has been read.
	reply.data = mBinaryReadBuffer;
	mBinaryReadBuffer.clear();
	return reply;
}
コード例 #12
0
ファイル: channel.c プロジェクト: routelastresort/juise
static int
mx_channel_read (mx_channel_t *mcp, char *buf, unsigned long bufsiz)
{
    int len;

    len = libssh2_channel_read(mcp->mc_channel, buf, bufsiz);

    DBG_POLL("C%u read %d", mcp->mc_id, len);
    if (len > 0) {
	slaxMemDump("chread: ", buf, len, ">", 0);
    } else {
	if (len == LIBSSH2_ERROR_SOCKET_RECV) {
	    if (mcp->mc_session)
		mcp->mc_session->mss_base.ms_state = MSS_FAILED;
	}
    }

    return len;
}
コード例 #13
0
static int netconf_read_until(LIBSSH2_CHANNEL *channel, const char *endtag,
                              char *buf, size_t buflen)
{
    ssize_t len;
    size_t rd = 0;
    char *endreply = NULL, *specialsequence = NULL;

    memset(buf, 0, buflen);

    do {
        len = libssh2_channel_read(channel, buf + rd, buflen - rd);
        if (LIBSSH2_ERROR_EAGAIN == len)
            continue;
        else if (len < 0) {
            fprintf(stderr, "libssh2_channel_read: %d\n", (int)len);
            return -1;
        }
        rd += len;

        /* read more data until we see a rpc-reply closing tag followed by
         * the special sequence ]]>]]> */

        /* really, this MUST be replaced with proper XML parsing! */

        endreply = strstr(buf, endtag);
        if (endreply)
            specialsequence = strstr(endreply, "]]>]]>");

    } while (!specialsequence && rd < buflen);

    if (!specialsequence) {
        fprintf(stderr, "%s: ]]>]]> not found! read buffer too small?\n", __func__);
        return -1;
    }

    /* discard the special sequence so that only XML is returned */
    rd = specialsequence - buf;
    buf[rd] = 0;

    return rd;
}
コード例 #14
0
ファイル: ssh.c プロジェクト: dmgctrl/libgit2
static int ssh_stream_read(
	git_smart_subtransport_stream *stream,
	char *buffer,
	size_t buf_size,
	size_t *bytes_read)
{
	ssh_stream *s = (ssh_stream *)stream;
	
	*bytes_read = 0;
	
	if (!s->sent_command && send_command(s) < 0)
		return -1;
	
	int rc = libssh2_channel_read(s->channel, buffer, buf_size);
	if (rc < 0)
		return -1;
	
	*bytes_read = rc;
	
	return 0;
}
コード例 #15
0
ファイル: sshexec.c プロジェクト: liusheng1985/sshexec
int read_channel(LIBSSH2_SESSION *session, LIBSSH2_CHANNEL *channel, int sock)
{
    char buffer[0x4000];
//    for(;;)
//    {
        int rc;
        do
        {
            if((rc = libssh2_channel_read(channel, buffer, sizeof(buffer))) > 0)
            {
                int i;
                for( i=0; i<rc; i++) fputc( buffer[i], stdout);
            }
        }
        while( rc > 0 );
//        if(libssh2_channel_eof(channel) == 1) break;
//        if(rc == LIBSSH2_ERROR_EAGAIN) waitsocket(sock, session);
//        else break;
//    }
    printf("\n");
}
コード例 #16
0
ファイル: libssh2.cpp プロジェクト: ly20119/mooon
int CLibssh2::read_channel(void* channel, std::ostream& out)
{
    int num_bytes = 0;
    LIBSSH2_CHANNEL* channel_ = static_cast<LIBSSH2_CHANNEL*>(channel);

    while (true)
    {
        char buffer[4096];
        int bytes = libssh2_channel_read(channel_, buffer, sizeof(buffer)-1);

        if (0 == bytes)
        {
            break; // connection closed now
        }
        else if (bytes > 0)
        {
            num_bytes += bytes;
            buffer[bytes] = '\0';
            out << buffer;
        }
        else
        {
            int errcode = get_session_errcode();

            if (errcode != LIBSSH2_ERROR_EAGAIN)
            {
                THROW_EXCEPTION(get_session_errmsg(), errcode);
            }
            else
            {
                if (!timedwait_socket())
                {
                    THROW_SYSCALL_EXCEPTION("channel read timeout", ETIMEDOUT, "poll");
                }
            }
        }
    }

    return num_bytes;
}
コード例 #17
0
ファイル: shellchannel.cpp プロジェクト: dd32/PonyEdit
ShellChannel::ReadReply ShellChannel::readUntil(const QByteArray& marker)
{
	ReadReply result;
	result.readAgain = false;

	//	Check if the buffer is already loaded and ready to go.
	int markerIndex = mReadBuffer.indexOf(marker);
	if (markerIndex == -1)
	{
		//	Actually do the read
		int rc = libssh2_channel_read(mHandle, mScratchBuffer, SSH_SHELL_BUFFER_SIZE);
		if (rc > 0)
			mReadBuffer.append(mScratchBuffer, rc);
		else if (rc == LIBSSH2_ERROR_EAGAIN)
		{
			result.readAgain = true;
			return result;
		}
		else if (rc == 0)
		{
			if (libssh2_channel_eof(mHandle))
				criticalError("Connection closed unexpectedly");
		}
		else
			criticalError("Failed to read from host");

		//	Check again to see if the buffer is ready to go.
		markerIndex = mReadBuffer.indexOf(marker);
	}

	//	If there's data ready to go, pack it into the reply.
	if (markerIndex > -1)
	{
		result.data = mReadBuffer.left(markerIndex);
		mReadBuffer = mReadBuffer.right(mReadBuffer.size() - (markerIndex + marker.length()));
	}

	return result;
}
コード例 #18
0
ファイル: ssh.c プロジェクト: Nemchinovrp/sonic-pi
static int ssh_stream_read(
	git_smart_subtransport_stream *stream,
	char *buffer,
	size_t buf_size,
	size_t *bytes_read)
{
	int rc;
	ssh_stream *s = (ssh_stream *)stream;

	*bytes_read = 0;

	if (!s->sent_command && send_command(s) < 0)
		return -1;

	if ((rc = libssh2_channel_read(s->channel, buffer, buf_size)) < LIBSSH2_ERROR_NONE) {
		ssh_error(s->session, "SSH could not read data");
		return -1;
	}

	/*
	 * If we can't get anything out of stdout, it's typically a
	 * not-found error, so read from stderr and signal EOF on
	 * stderr.
	 */
	if (rc == 0) {
		if ((rc = libssh2_channel_read_stderr(s->channel, buffer, buf_size)) > 0) {
			giterr_set(GITERR_SSH, "%*s", rc, buffer);
			return GIT_EEOF;
		} else if (rc < LIBSSH2_ERROR_NONE) {
			ssh_error(s->session, "SSH could not read stderr");
			return -1;
		}
	}


	*bytes_read = rc;

	return 0;
}
コード例 #19
0
ファイル: ssh.c プロジェクト: Nangal/libgit2
static int ssh_stream_read(
	git_smart_subtransport_stream *stream,
	char *buffer,
	size_t buf_size,
	size_t *bytes_read)
{
	int rc;
	ssh_stream *s = (ssh_stream *)stream;

	*bytes_read = 0;

	if (!s->sent_command && send_command(s) < 0)
		return -1;

	if ((rc = libssh2_channel_read(s->channel, buffer, buf_size)) < LIBSSH2_ERROR_NONE) {
		ssh_error(s->session, "SSH could not read data");;
		return -1;
	}

	*bytes_read = rc;

	return 0;
}
コード例 #20
0
static void
ssh_relay_cb(obfsproxyssh_client_session_t *session)
{
	obfsproxyssh_t *state = session->client->state;
	char *p;
	ssize_t rval;

	p = session->ssh_rx_buf;
	for (;;) {
		rval = libssh2_channel_read(session->ssh_channel, p,
					OBFSPROXYSSH_CLIENT_READ_SZ);
		if (LIBSSH2_ERROR_EAGAIN == rval || 0 == rval)
			break;
		else if (rval < 0) {
			log_f(state, "RELAY: Error: %s Channel read failed (%d)",
					bdata(session->ssh_addr), rval);
			ssh_relay_event_cb(session->ssh_ev, BEV_EVENT_ERROR, session);
			return;
		}

		bufferevent_write(session->socks_ev, p, rval);
		memset(p, 0, OBFSPROXYSSH_CLIENT_READ_SZ);
	}
}
コード例 #21
0
ファイル: sshTunnel.cpp プロジェクト: GHnubsST/pgadmin3
void *
CSubThread::Entry()
{
	fd_set fds;
	struct timeval tv;
	ssize_t len, wr;
	char buf[20480];
	int rc, i = 0;

	const char *shost = inet_ntoa(m_sin.sin_addr);
	unsigned int sport = ntohs(m_sin.sin_port);

	wxLogInfo(wxT("Forwarding connection from %s:%d to %s:%d"), wxString(inet_ntoa(m_sin.sin_addr), wxConvLibc).c_str(),
	          sport, m_remote_desthost.c_str(), m_remote_destport);

	/* Must use blocking here to avoid connect errors */
	//libssh2_session_set_blocking(m_subThreadSession, 1);

	while((m_channel = libssh2_channel_direct_tcpip_ex(m_subThreadSession, m_remote_desthost.mb_str(),
	                   m_remote_destport, shost, sport)) == NULL)
	{
		rc = libssh2_session_last_error(m_subThreadSession, NULL, NULL, 0);
		if (rc == LIBSSH2_ERROR_EAGAIN)
			Sleep(10);
		else
			break;
	}

	/* Must use non-blocking IO hereafter due to the current libssh2 API */
	libssh2_session_set_blocking(m_subThreadSession, 0);

	if (!m_channel)
	{
		wxLogInfo(_("SSH error: Could not open a direct-tcpip channel!"));
		goto shutdown;
	}

	while (1)
	{
		FD_ZERO(&fds);
		FD_SET(m_forwardsock, &fds);
		tv.tv_sec = 0;
		tv.tv_usec = 100000;
		rc = select(m_forwardsock + 1, &fds, NULL, NULL, &tv);
		memset(buf, 0, sizeof(buf));
		if (-1 == rc)
		{
			wxLogInfo(_("SSH error: select failed with error code %d"), wxSysErrorCode());
			goto shutdown;
		}
		if (rc && FD_ISSET(m_forwardsock, &fds))
		{
			len = recv(m_forwardsock, buf, sizeof(buf), 0);
			if (len < 0)
			{
				wxLogInfo(_("SSH error: read failed with error code %d"), wxSysErrorCode());
				goto shutdown;
			}
			else if (0 == len)
			{
				wxLogInfo(_("The client at %s:%d disconnected!"), wxString(inet_ntoa(m_sin.sin_addr), wxConvLibc).c_str(), sport);
				goto shutdown;
			}
			wr = 0;
			do
			{
				i = libssh2_channel_write(m_channel, buf, len);

				if (i < 0)
				{
					wxLogInfo(_("SSH error: libssh2_channel_write with error code %d"), i);
					goto shutdown;
				}
				wr += i;
			}
			while (i > 0 && wr < len);
		}
		while (1)
		{
			len = libssh2_channel_read(m_channel, buf, sizeof(buf));

			if (LIBSSH2_ERROR_EAGAIN == len)
				break;
			else if (len < 0)
			{
				wxLogInfo(_("SSH error: libssh2_channel_read with error code %d"), (int)len);
				goto shutdown;
			}
			wr = 0;
			while (wr < len)
			{
				i = send(m_forwardsock, buf + wr, len - wr, 0);
				if (i <= 0)
				{
					wxLogInfo(_("SSH error: write failed with error code %d"), wxSysErrorCode());
					goto shutdown;
				}
				wr += i;
			}
			if (libssh2_channel_eof(m_channel))
			{
				wxLogInfo(_("Connection at %s:%d disconnected by server"),
				          wxString(inet_ntoa(m_sin.sin_addr), wxConvLibc).c_str(), sport);
				goto shutdown;
			}
		}
	}
shutdown:
#ifdef WIN32
	closesocket(m_forwardsock);
#else
	close(m_forwardsock);
#endif

	if (m_channel)
	{
		libssh2_channel_close(m_channel);
		libssh2_channel_free(m_channel);
		m_channel = NULL;
	}

	return NULL;
}
コード例 #22
0
static int exec_channel_command_exec(SSH_SESSION* p_session, const char* command, int (*callback)(char*, const char*, void*), void* obj)
{
    char* buffer;
    int buffer_length = COMMAND_RESULT_BUFFER_LENGTH;
    int ec;
    int result_code;
    LIBSSH2_CHANNEL* channel;
    
    while((ec = libssh2_channel_exec(p_session->session_param->channel, command)) == LIBSSH2_ERROR_EAGAIN)
    {
        waitsocket(p_session->session_param->sock, p_session->session_param->session, TIMEOUT_SEC);
    }
    if(ec < 0)
    {
        debug_log(SSH_TERMINAL_COMMAND_EXEC_ERROR, "sync_command_exec : channel exec failed.");
        return SSH_TERMINAL_COMMAND_EXEC_ERROR;
    }
    
    buffer = (char*)malloc(sizeof(char) * (buffer_length + 1));
    
    while(1)
    {
        do{
            memset(buffer, 0, buffer_length + 1);
            ec = libssh2_channel_read(p_session->session_param->channel, buffer, buffer_length);
            if(ec == 0)
            {
                ec = libssh2_channel_read_stderr(p_session->session_param->channel, buffer, buffer_length);
            }
            if(ec > 0)
            {
                callback(buffer, command, obj);
            }
        }
        while(ec > 0);
        
        if(ec == LIBSSH2_ERROR_EAGAIN)
        {
            waitsocket(p_session->session_param->sock, p_session->session_param->session, TIMEOUT_SEC);
        }
        else
        {
            break;
        }
    }
    free(buffer);
    if(ec < 0)
    {
        debug_log(SSH_TERMINAL_CHANNEL_READ_ERROR, "sync_command_exec : channel read failed.");
        result_code = SSH_TERMINAL_CHANNEL_READ_ERROR;
    }
    else
    {
        result_code = 0;
    }
    
    while(libssh2_channel_close(p_session->session_param->channel) == LIBSSH2_ERROR_EAGAIN)
    {
        waitsocket(p_session->session_param->sock, p_session->session_param->session, TIMEOUT_SEC);
    }
    
    libssh2_channel_free(p_session->session_param->channel);
    
    while((channel = libssh2_channel_open_session(p_session->session_param->session)) == NULL &&
          libssh2_session_last_error(p_session->session_param->session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN)
    {
        waitsocket(p_session->session_param->sock, p_session->session_param->session, TIMEOUT_SEC);
    }
    if(channel == NULL)
    {
        result_code = SSH_TERMINAL_CHANNEL_OPEN_ERROR;
    }
    
    p_session->session_param->channel = channel;
    
    return result_code;
}
コード例 #23
0
/* example ssh.run["ls /"] */
static int	ssh_run(DC_ITEM *item, AGENT_RESULT *result, const char *encoding)
{
	const char	*__function_name = "ssh_run";
	zbx_sock_t	s;
	LIBSSH2_SESSION	*session;
	LIBSSH2_CHANNEL	*channel;
	int		auth_pw = 0, rc, ret = NOTSUPPORTED,
			exitcode, bytecount = 0;
	char		buffer[MAX_BUFFER_LEN], buf[16], *userauthlist,
			*publickey = NULL, *privatekey = NULL, *ssherr;
	size_t		sz;

	zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);

	if (FAIL == zbx_tcp_connect(&s, CONFIG_SOURCE_IP, item->interface.addr, item->interface.port, 0))
	{
		SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Cannot connect to SSH server: %s",
				zbx_tcp_strerror()));
		goto close;
	}

	/* initializes an SSH session object */
	if (NULL == (session = libssh2_session_init()))
	{
		SET_MSG_RESULT(result, zbx_strdup(NULL, "Cannot initialize SSH session"));
		goto tcp_close;
	}

	/* set blocking mode on session */
	libssh2_session_set_blocking(session, 1);

	/* Create a session instance and start it up. This will trade welcome */
	/* banners, exchange keys, and setup crypto, compression, and MAC layers */
	if (0 != libssh2_session_startup(session, s.socket))
	{
		libssh2_session_last_error(session, &ssherr, NULL, 0);
		SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Cannot establish SSH session: %s", ssherr));
		goto session_free;
	}

	/* check what authentication methods are available */
	if (NULL != (userauthlist = libssh2_userauth_list(session, item->username, strlen(item->username))))
	{
		if (NULL != strstr(userauthlist, "password"))
			auth_pw |= 1;
		if (NULL != strstr(userauthlist, "keyboard-interactive"))
			auth_pw |= 2;
		if (NULL != strstr(userauthlist, "publickey"))
			auth_pw |= 4;
	}
	else
	{
		libssh2_session_last_error(session, &ssherr, NULL, 0);
		SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Cannot obtain authentication methods: %s", ssherr));
		goto session_close;
	}

	zabbix_log(LOG_LEVEL_DEBUG, "%s() supported authentication methods:'%s'", __function_name, userauthlist);

	switch (item->authtype)
	{
		case ITEM_AUTHTYPE_PASSWORD:
			if (auth_pw & 1)
			{
				/* we could authenticate via password */
				if (0 != libssh2_userauth_password(session, item->username, item->password))
				{
					libssh2_session_last_error(session, &ssherr, NULL, 0);
					SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Password authentication failed: %s",
							ssherr));
					goto session_close;
				}
				else
					zabbix_log(LOG_LEVEL_DEBUG, "%s() password authentication succeeded",
							__function_name);
			}
			else if (auth_pw & 2)
			{
				/* or via keyboard-interactive */
				password = item->password;
				if (0 != libssh2_userauth_keyboard_interactive(session, item->username, &kbd_callback))
				{
					libssh2_session_last_error(session, &ssherr, NULL, 0);
					SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Keyboard-interactive authentication"
							" failed: %s", ssherr));
					goto session_close;
				}
				else
					zabbix_log(LOG_LEVEL_DEBUG, "%s() keyboard-interactive authentication succeeded",
							__function_name);
			}
			else
			{
				SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Unsupported authentication method."
						" Supported methods: %s", userauthlist));
				goto session_close;
			}
			break;
		case ITEM_AUTHTYPE_PUBLICKEY:
			if (auth_pw & 4)
			{
				if (NULL == CONFIG_SSH_KEY_LOCATION)
				{
					SET_MSG_RESULT(result, zbx_strdup(NULL, "Authentication by public key failed."
							" SSHKeyLocation option is not set"));
					goto session_close;
				}

				/* or by public key */
				publickey = zbx_dsprintf(publickey, "%s/%s", CONFIG_SSH_KEY_LOCATION, item->publickey);
				privatekey = zbx_dsprintf(privatekey, "%s/%s", CONFIG_SSH_KEY_LOCATION,
						item->privatekey);

				if (SUCCEED != zbx_is_regular_file(publickey))
				{
					SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Cannot access public key file %s",
							publickey));
					goto session_close;
				}

				if (SUCCEED != zbx_is_regular_file(privatekey))
				{
					SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Cannot access private key file %s",
							privatekey));
					goto session_close;
				}

				rc = libssh2_userauth_publickey_fromfile(session, item->username, publickey,
						privatekey, item->password);
				zbx_free(publickey);
				zbx_free(privatekey);

				if (0 != rc)
				{
					libssh2_session_last_error(session, &ssherr, NULL, 0);
					SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Public key authentication failed:"
							" %s", ssherr));
					goto session_close;
				}
				else
					zabbix_log(LOG_LEVEL_DEBUG, "%s() authentication by public key succeeded",
							__function_name);
			}
			else
			{
				SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Unsupported authentication method."
						" Supported methods: %s", userauthlist));
				goto session_close;
			}
			break;
	}

	/* exec non-blocking on the remove host */
	while (NULL == (channel = libssh2_channel_open_session(session)))
	{
		switch (libssh2_session_last_error(session, NULL, NULL, 0))
		{
			/* marked for non-blocking I/O but the call would block. */
			case LIBSSH2_ERROR_EAGAIN:
				waitsocket(s.socket, session);
				continue;
			default:
				SET_MSG_RESULT(result, zbx_strdup(NULL, "Cannot establish generic session channel"));
				goto session_close;
		}
	}

	dos2unix(item->params);	/* CR+LF (Windows) => LF (Unix) */
	/* request a shell on a channel and execute command */
	while (0 != (rc = libssh2_channel_exec(channel, item->params)))
	{
		switch (rc)
		{
			case LIBSSH2_ERROR_EAGAIN:
				waitsocket(s.socket, session);
				continue;
			default:
				SET_MSG_RESULT(result, zbx_strdup(NULL, "Cannot request a shell"));
				goto channel_close;
		}
	}

	for (;;)
	{
		/* loop until we block */
		do
		{
			if (0 < (rc = libssh2_channel_read(channel, buf, sizeof(buf))))
			{
				sz = (size_t)rc;
				if (sz > MAX_BUFFER_LEN - (bytecount + 1))
					sz = MAX_BUFFER_LEN - (bytecount + 1);
				if (0 == sz)
					continue;

				memcpy(buffer + bytecount, buf, sz);
				bytecount += sz;
			}
		}
		while (rc > 0);

		/* this is due to blocking that would occur otherwise so we loop on
		 * this condition
		 */
		if (LIBSSH2_ERROR_EAGAIN == rc)
			waitsocket(s.socket, session);
		else if (rc < 0)
		{
			SET_MSG_RESULT(result, zbx_strdup(NULL, "Cannot read data from SSH server"));
			goto channel_close;
		}
		else
			break;
	}

	buffer[bytecount] = '\0';
	SET_STR_RESULT(result, convert_to_utf8(buffer, bytecount, encoding));

	ret = SYSINFO_RET_OK;

channel_close:
	/* close an active data channel */
	exitcode = 127;
	while (0 != (rc = libssh2_channel_close(channel)))
	{
		switch (rc)
		{
			case LIBSSH2_ERROR_EAGAIN:
				waitsocket(s.socket, session);
				continue;
			default:
				libssh2_session_last_error(session, &ssherr, NULL, 0);
				zabbix_log(LOG_LEVEL_WARNING, "%s() cannot close generic session channel: %s",
						__function_name, ssherr);
				break;
		}
	}

	if (0 == rc)
		exitcode = libssh2_channel_get_exit_status(channel);
	zabbix_log(LOG_LEVEL_DEBUG, "%s() exitcode: %d bytecount: %d",
			__function_name, exitcode, bytecount);

	libssh2_channel_free(channel);
	channel = NULL;

session_close:
	libssh2_session_disconnect(session, "Normal Shutdown");

session_free:
	libssh2_session_free(session);

tcp_close:
	zbx_tcp_close(&s);

close:
	zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));

	return ret;
}
コード例 #24
0
ファイル: ssh_client.c プロジェクト: baskard/guacamole-server
void* ssh_client_thread(void* data) {

    guac_client* client = (guac_client*) data;
    ssh_guac_client_data* client_data = (ssh_guac_client_data*) client->data;

    char name[1024];

    guac_socket* socket = client->socket;
    char buffer[8192];
    int bytes_read = -1234;

    int socket_fd;
    int stdout_fd = client_data->term->stdout_pipe_fd[1];

    pthread_t input_thread;

    libssh2_init(0);

    /* Get username */
    if (client_data->username[0] == 0)
        prompt(client, "Login as: ", client_data->username, sizeof(client_data->username), true);

    /* Send new name */
    snprintf(name, sizeof(name)-1, "%s@%s", client_data->username, client_data->hostname);
    guac_protocol_send_name(socket, name);

    /* If key specified, import */
    if (client_data->key_base64[0] != 0) {

        /* Attempt to read key without passphrase */
        client_data->key = ssh_key_alloc(client_data->key_base64,
                strlen(client_data->key_base64), "");

        /* On failure, attempt with passphrase */
        if (client_data->key == NULL) {

            /* Prompt for passphrase if missing */
            if (client_data->key_passphrase[0] == 0)
                prompt(client, "Key passphrase: ", client_data->key_passphrase,
                        sizeof(client_data->key_passphrase), false);

            /* Import key with passphrase */
            client_data->key = ssh_key_alloc(client_data->key_base64,
                    strlen(client_data->key_base64),
                    client_data->key_passphrase);

            /* If still failing, give up */
            if (client_data->key == NULL) {
                guac_client_log_error(client, "Auth key import failed.");
                return NULL;
            }

        } /* end decrypt key with passphrase */

        /* Success */
        guac_client_log_info(client, "Auth key successfully imported.");

    } /* end if key given */

    /* Otherwise, get password if not provided */
    else if (client_data->password[0] == 0)
        prompt(client, "Password: "******"\x1B[H\x1B[J", 6);

    /* Open SSH session */
    client_data->session = __guac_ssh_create_session(client, &socket_fd);
    if (client_data->session == NULL) {
        /* Already aborted within __guac_ssh_create_session() */
        return NULL;
    }

    /* Open channel for terminal */
    client_data->term_channel = libssh2_channel_open_session(client_data->session);
    if (client_data->term_channel == NULL) {
        guac_client_abort(client, GUAC_PROTOCOL_STATUS_UPSTREAM_ERROR, "Unable to open terminal channel.");
        return NULL;
    }

#ifdef ENABLE_SSH_AGENT
    /* Start SSH agent forwarding, if enabled */
    if (client_data->enable_agent) {
        libssh2_session_callback_set(client_data->session,
                LIBSSH2_CALLBACK_AUTH_AGENT, (void*) ssh_auth_agent_callback);

        /* Request agent forwarding */
        if (libssh2_channel_request_auth_agent(client_data->term_channel))
            guac_client_log_error(client, "Agent forwarding request failed");
        else
            guac_client_log_info(client, "Agent forwarding enabled.");
    }

    client_data->auth_agent = NULL;
#endif

    /* Start SFTP session as well, if enabled */
    if (client_data->enable_sftp) {

        /* Create SSH session specific for SFTP */
        guac_client_log_info(client, "Reconnecting for SFTP...");
        client_data->sftp_ssh_session = __guac_ssh_create_session(client, NULL);
        if (client_data->sftp_ssh_session == NULL) {
            /* Already aborted within __guac_ssh_create_session() */
            return NULL;
        }

        /* Request SFTP */
        client_data->sftp_session = libssh2_sftp_init(client_data->sftp_ssh_session);
        if (client_data->sftp_session == NULL) {
            guac_client_abort(client, GUAC_PROTOCOL_STATUS_UPSTREAM_ERROR, "Unable to start SFTP session.");
            return NULL;
        }

        /* Set file handler */
        client->file_handler = guac_sftp_file_handler;

        guac_client_log_info(client, "SFTP session initialized");

    }

    /* Request PTY */
    if (libssh2_channel_request_pty_ex(client_data->term_channel, "linux", sizeof("linux")-1, NULL, 0,
            client_data->term->term_width, client_data->term->term_height, 0, 0)) {
        guac_client_abort(client, GUAC_PROTOCOL_STATUS_UPSTREAM_ERROR, "Unable to allocate PTY.");
        return NULL;
    }

    /* Request shell */
    if (libssh2_channel_shell(client_data->term_channel)) {
        guac_client_abort(client, GUAC_PROTOCOL_STATUS_UPSTREAM_ERROR, "Unable to associate shell with PTY.");
        return NULL;
    }

    /* Logged in */
    guac_client_log_info(client, "SSH connection successful.");

    /* Start input thread */
    if (pthread_create(&(input_thread), NULL, ssh_input_thread, (void*) client)) {
        guac_client_abort(client, GUAC_PROTOCOL_STATUS_SERVER_ERROR, "Unable to start input thread");
        return NULL;
    }

    /* Set non-blocking */
    libssh2_session_set_blocking(client_data->session, 0);

    /* While data available, write to terminal */
    bytes_read = 0;
    while (!libssh2_channel_eof(client_data->term_channel)) {

        /* Track total amount of data read */
        int total_read = 0;

        /* Read terminal data */
        bytes_read = libssh2_channel_read(client_data->term_channel,
                buffer, sizeof(buffer));

        /* Attempt to write data received. Exit on failure. */
        if (bytes_read > 0) {
            int written = guac_terminal_write_all(stdout_fd, buffer, bytes_read);
            if (written < 0)
                break;

            total_read += bytes_read;
        }

        else if (bytes_read < 0 && bytes_read != LIBSSH2_ERROR_EAGAIN)
            break;

#ifdef ENABLE_SSH_AGENT
        /* If agent open, handle any agent packets */
        if (client_data->auth_agent != NULL) {
            bytes_read = ssh_auth_agent_read(client_data->auth_agent);
            if (bytes_read > 0)
                total_read += bytes_read;
            else if (bytes_read < 0 && bytes_read != LIBSSH2_ERROR_EAGAIN)
                client_data->auth_agent = NULL;
        }
#endif

        /* Wait for more data if reads turn up empty */
        if (total_read == 0) {
            fd_set fds;
            struct timeval timeout;

            FD_ZERO(&fds);
            FD_SET(socket_fd, &fds);

            /* Wait for one second */
            timeout.tv_sec = 1;
            timeout.tv_usec = 0;

            if (select(socket_fd+1, &fds, NULL, NULL, &timeout) < 0)
                break;
        }

    }

    /* Kill client and Wait for input thread to die */
    guac_client_stop(client);
    pthread_join(input_thread, NULL);

    guac_client_log_info(client, "SSH connection ended.");
    return NULL;

}
コード例 #25
0
ファイル: ssh.c プロジェクト: 3mao/stool
int ssh_cmd(SSH * pSsh,char * pCmdstr)
{
		int ret=0;
		int exitcode;
		char *exitsignal=(char *)"none";

	if (NULL==pSsh || NULL==pCmdstr)
	{
		return 0;
	}

	while( (pSsh->channel = libssh2_channel_open_session(pSsh->session)) == NULL &&
		libssh2_session_last_error(pSsh->session,NULL,NULL,0) ==
		LIBSSH2_ERROR_EAGAIN )
	{
		waitsocket(pSsh->sock_fd, pSsh->session);
	}
	if( pSsh->channel == NULL )
	{
		fprintf(stderr,"Error\n");
		exit( 1 );
	}
	while( (ret = libssh2_channel_exec(pSsh->channel, pCmdstr)) ==
		LIBSSH2_ERROR_EAGAIN )
	{
		waitsocket(pSsh->sock_fd, pSsh->session);
	}
	if( ret != 0 )
	{
		fprintf(stderr,"Error\n");
		exit( 1 );
	}

	for( ;; )
    {
        /* loop until we block */
        int rc;
        do
        {
            char buffer[0x4000];
            rc = libssh2_channel_read( pSsh->channel, buffer, sizeof(buffer) );
            if( rc > 0 )
            {
                int i;
                
                for( i=0; i < rc; ++i )
                    fputc( buffer[i], stdout);
                fprintf(stderr, "\n");
            }
            else {
                if( ret != LIBSSH2_ERROR_EAGAIN )
                    /* no need to output this for the EAGAIN case */
                    fprintf(stderr, "libssh2_channel_read returned %d\n", rc);
            }
        }
        while( ret > 0 );

        /* this is due to blocking that would occur otherwise so we loop on
           this condition */
        if( rc == LIBSSH2_ERROR_EAGAIN )
        {
            waitsocket(pSsh->sock_fd, pSsh->session);
        }
        else
            break;
    }
    exitcode = 127;
    while( (ret = libssh2_channel_close(pSsh->channel)) == LIBSSH2_ERROR_EAGAIN )
        waitsocket(pSsh->sock_fd, pSsh->session);

    if( ret == 0 )
    {
        exitcode = libssh2_channel_get_exit_status( pSsh->channel );
        libssh2_channel_get_exit_signal(pSsh->channel, &exitsignal,
                                        NULL, NULL, NULL, NULL, NULL);
    }

    if (exitsignal)
        fprintf(stderr, "\nGot signal: %s\n", exitsignal);
   

	fprintf(stderr,"\n*ssh_cmd::pcmdstr=%s\n",pCmdstr);


	return 0;
}
コード例 #26
0
ファイル: scanner.cpp プロジェクト: kilitary/scanner
void* thread_func(void* arg)
{
    int sockfd;
    sockaddr_in serv_addr;
    char curhost[26];
    boost::random::uniform_int_distribution<> dist(1, 9999999999999);//numeric_limits< unsigned long>::max());
    boost::random::mt19937 gen((int)pthread_self()+(int)time(NULL));
    LIBSSH2_SESSION *session=0;
    // HCkSsh ssh;
    srand((int)pthread_self()+rand()+time(NULL));
    while (do_scan)
    {
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
            deb("ERROR opening socket: %s\r\n",fmterr());
        setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
        long flags;
        flags		  = fcntl(sockfd, F_GETFL, 0);
        fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
        bzero((char *) &serv_addr, sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_port = htons(22);
        do
        {
            serv_addr.sin_addr.s_addr =   dist(gen);//getrnd(0,100000000000000);//rand();//inet_addr("195.2.253.204")
        }
        while (ischecking(serv_addr.sin_addr.s_addr));
        strncpy(curhost, inet_ntoa(serv_addr.sin_addr), sizeof(curhost));
        addchecking(serv_addr.sin_addr.s_addr);
        unsigned long chkdist=0;
        chkdist=dist(gen);
        int ret;
        //   deb("\rconnecting %16s ", inet_ntoa(serv_addr.sin_addr));
        ret=connect(sockfd, (struct sockaddr*) &serv_addr, sizeof( serv_addr));
        fd_set fds;
        //deb("ret:%d errno:%s (%d)\r\n",ret,strerror(errno),errno);
        // sleep(1);
        FD_ZERO(&fds);
        FD_SET(sockfd, &fds);
        tv.tv_sec = 2;
        tv.tv_usec = 0;
        char buf[1024];
        if (ret==0 || (ret==-1 && errno == EINPROGRESS))
        {
            ipscanned++;
            int res = select(sockfd+1,  &fds,&fds, 0, &tv);
            //deb("res:%d errno:%s (%d)\r\n",res,strerror(errno),errno);
            if (res < 0 && errno != EINTR)
            {
                //      deb("\r\n%s Error connecting %d - %s\n\r",
                //  	curhost, errno, strerror(errno));
            }
            else if (res > 0)
            {
                flags &= (~O_NONBLOCK);
                if ( fcntl(sockfd, F_SETFL, flags) < 0)
                {
                    deb("Error fcntl(..., F_SETFL) (%s)\n", strerror(errno));
                }
                int rcv;
                memset(buf, 0, sizeof(buf));
                rcv = recv(sockfd, buf, sizeof(buf), MSG_PEEK);
                //if (rcv>0)
                //  buf[rcv]=0;
                // if (rcv>0)
                // deb("rcv: %d %s\r\n",rcv, trim(buf));
                const char *username="******";
                const char *password="******";
                const char *sftppath="/tmp";
                int rc;
                const char *fingerprint;
                session = libssh2_session_init();
                libssh2_session_set_blocking(session, 1);
                int numTry=0;
                while (session>0 && (rc = libssh2_session_handshake(session, sockfd)) ==
                        LIBSSH2_ERROR_EAGAIN);
                int u;
                LIBSSH2_CHANNEL *channel=0;
                if (rc)
                {
                    if (rc!=-43)
                        deb("%16s failure establishing SSH session: %d [rnd: %lu, checking: %d]\n",
                            curhost,rc,chkdist,checking.size());
                    //return -1;
                }
                else
                {
                    totscanned++;
                    fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
                    deb( "%16s %-50s ", inet_ntoa(serv_addr.sin_addr),
                         trim(buf));
                    for (int i = 0; i < 20; i++)
                    {
                        deb(KYEL "%02X " RESET, (unsigned char)fingerprint[i]);
                    }
                    deb( "\n");
                    char* passwords[]={"root","admin","toor","r00t","adm",
                                       "secure","pwd","password","god"
                                      };
                    for ( u=0;u<3;u++)
                    {
                        if (libssh2_userauth_password(session, username, passwords[u]))
                        {
                            //       deb( "%16s " KRED "Authentication by password failed. [%s]\n"
                            //         RESET, inet_ntoa(serv_addr.sin_addr),passwords[u]);
                            continue;
                        }
                        else
                        {
                            deb(KCYN "%16s authenticated %s:%s \r\n" RESET,
                                inet_ntoa(serv_addr.sin_addr),
                                username,passwords[u],totscanned);
                            struct stat fileinfo;
                            channel = libssh2_scp_recv(session, "/etc/services", &fileinfo);
                            if (!channel)
                            {
                                deb(KRED "%16s Unable to open a session: %d\r\n" RESET,
                                    inet_ntoa(serv_addr.sin_addr),
                                    libssh2_session_last_errno(session));
                                break;
                            }
                            if (!fileinfo.st_size)
                            {
                                deb(KGRN "%16s router/modem\r\n" RESET, inet_ntoa(serv_addr.sin_addr),
                                    fileinfo.st_size);
                                fdeb("%s %s:%s [router/modem (%s)]\r\n", inet_ntoa(serv_addr.sin_addr),
                                     username,passwords[u],trim(buf));
                            }
                            else
                            {
                                deb(KGRN "%16s unknown device fs:%d [%s]\r\n" RESET,
                                    inet_ntoa(serv_addr.sin_addr),
                                    fileinfo.st_size,trim(buf));
                                fdeb("%s %s:%s unknown (%s)\r\n", inet_ntoa(serv_addr.sin_addr),
                                     username,passwords[u],trim( buf));
                            }
                            channel = libssh2_scp_recv(session, "/proc/cpuinfo", &fileinfo);
                            if (!channel)
                            {
                                //  deb(KRED "\r\nUnable to open a session: %d\r\n" RESET,
                                //      libssh2_session_last_errno(session));
                                //break;
                            }
                            else
                            {
                                int got=0;
                                char mem[1024];
                                int amount=sizeof(mem);
                                while (got < fileinfo.st_size)
                                {
                                    if ((fileinfo.st_size -got) < amount)
                                    {
                                        amount = fileinfo.st_size -got;
                                    }
                                    rc = libssh2_channel_read(channel, mem, amount);
                                    if (rc > 0)
                                    {
                                        deb("mem:%p rc:%d", mem, rc);
                                    }
                                    else if (rc < 0)
                                    {
                                        deb("libssh2_channel_read() failed: %d\n", rc);
                                        break;
                                    }
                                    got += rc;
                                }
                                if (mem[0])
                                    deb("mem: %s", mem);
                            }
                            founds++;
                            try
                            {
                                MySexec sexec;
                                sexec.SetSSHHost( curhost );
                                int ret_code = sexec.SetTimeout(17);
                                if (ret_code) throw("\r\nfailed: SetTimeout\r\n");
                                ret_code = sexec.SetSSHUser(username);
                                if (ret_code) throw("\r\nfailed: SetSSHUser\r\n");
                                ret_code = sexec.SetSSHPassword(passwords[u]);
                                if (ret_code) throw("\r\nfailed: SetSSHPassword()\r\n");
                                ret_code = sexec.SSHLogon(curhost ,22);
                                if (ret_code) throw("\r\nfailed: SSHLogon\r\n");
                                ret_code = sexec.Execute("ls -l");
                                if (ret_code) throw("\r\Execute:%d",ret_code);
                                //sleep(2);
                                deb(KGRN "executed on %s\r\n" RESET, curhost);
                               // fdeb("\r\n[host %s]\r\n",curhost);
                                // exit(0);
                            }
                            catch ( const char *str )
                            {
                                deb(KRED "in except: %s\r\n" RESET,str);
                            }
                            //exit(0);
                        }
                    }
                    //  free(fingerprint);
                }
                if (channel)
                    libssh2_channel_free(channel);
                if (session)
                {
                    // libssh2_session_disconnect(session, "Norm");
                    libssh2_session_free(session);
                }
                /*   ssh = CkSsh_Create();
                   bool success;
                   CkSsh_UnlockComponent(ssh,"Anything for 30-day trial");
                   success = CkSsh_Connect(ssh,inet_ntoa(serv_addr.sin_addr),22);
                   CkSsh_putIdleTimeoutMs(ssh,5000);
                   success = CkSsh_AuthenticatePw(ssh,"root","root");
                   if (success != TRUE)
                   {
                       deb("%s\n",CkSsh_lastErrorText(ssh));
                       return 0;
                   }
                   int channelNum;
                   channelNum = CkSsh_OpenSessionChannel(ssh);
                   if (channelNum < 0)
                   {
                       deb("%s\n",CkSsh_lastErrorText(ssh));
                      return 0;
                   }
                   success = CkSsh_SendReqExec(ssh,channelNum,"uname -a");
                   if (success != TRUE)
                   {
                       deb("%s\n",CkSsh_lastErrorText(ssh));
                       return 0;
                   }
                   //  Call ChannelReceiveToClose to read
                   //  output until the server's corresponding "channel close" is received.
                   success = CkSsh_ChannelReceiveToClose(ssh,channelNum);
                   if (success != TRUE)
                   {
                       deb("%s\n",CkSsh_lastErrorText(ssh));
                      return 0;
                   }
                   //  Let's pickup the accumulated output of the command:
                   const char * cmdOutput;
                   cmdOutput = CkSsh_getReceivedText(ssh,channelNum,"ansi");
                   if (cmdOutput == 0 )
                   {
                       deb("%s\n",CkSsh_lastErrorText(ssh));
                       return 0;
                   }
                   //  Display the remote shell's command output:
                   deb("%s\n",cmdOutput);
                   //  Disconnect
                   CkSsh_Disconnect(ssh);
                   CkSsh_Dispose(ssh);*/
            }
        }
コード例 #27
0
ファイル: parser.cpp プロジェクト: alexadmin/main
int Parser::runCommand(QString command)
{
    // command channel
    //------------setup channel ----------------------
    LIBSSH2_CHANNEL *channel = NULL;
    channel = libssh2_channel_open_session(session_);
    if ( channel == NULL )
    {
        qDebug()<<"Failed to open a new channel\n";
        socket_->disconnectFromHost();
        return -1;
    }

    /* Force Data to on STDOUT and STDERR to be on seperate channels
     * read individually with *_read and *_read_stderr functions */
    libssh2_channel_handle_extended_data(channel,LIBSSH2_CHANNEL_EXTENDED_DATA_NORMAL);

    libssh2_channel_set_blocking(channel, 1);

    {
    int rc;
    while ((rc=libssh2_channel_exec(channel, command.toLocal8Bit().constData()))==LIBSSH2_ERROR_EAGAIN );
    if (rc)
    {
        return -1;
    }


    //-------read channel-----------
    int read;

    QString stdout_str;
    QString stderr_str;
    while(true)
    {
        //qDebug("libssh2_channel_read() >>>");

        {
            QByteArray byte_array;
            byte_array.resize(4096);
            char* buffer=byte_array.data();
            int buffer_size=byte_array.size();
            read = libssh2_channel_read(channel, buffer, buffer_size-10);
            if(read>0)
            {
                QByteArray debug = QByteArray(buffer, read);
                stdout_str.append(debug);
            }
            if(LIBSSH2_ERROR_EAGAIN == read)
            {
                qDebug("LIBSSH2_ERROR_EAGAIN");
                break;
            }
            else if(read  < 0)
            {
                qDebug(" error reading from std channel");
                closeChannel(channel);
                goto next_channel;
            }
        }
        {
            QByteArray byte_array;
            byte_array.resize(4096);
            char* buffer=byte_array.data();
            int buffer_size=byte_array.size();

read = libssh2_channel_read_stderr(channel, buffer, buffer_size-10);
            if(read>0)
            {
                QByteArray debug = QByteArray(buffer, read);
                stderr_str.append(debug);
            }
            if(LIBSSH2_ERROR_EAGAIN == read)
            {
                qDebug("LIBSSH2_ERROR_EAGAIN");
                break;
            }
            else if(read  < 0)
            {
                qDebug(" error reading from stderr channel");
                closeChannel(channel);
                goto next_channel;
            }
        }


        int i = libssh2_channel_eof(channel);
        if(i)
        {
            //qDebug("libssh2_channel_eof %i", i);
            closeChannel(channel);
            goto next_channel;
        }
    }
    next_channel:
    if(!stdout_str.isEmpty())
    {
        qDebug()<<"STDOUT:\n"<<stdout_str;
    }
    if(!stderr_str.isEmpty())
    {
        qDebug()<<"STDERR:\n"<<stderr_str;
    }
    }
    return 1;
}
コード例 #28
0
ファイル: ssh.c プロジェクト: cianmcgovern/remote-notify-base
int execute_command(struct remote *rm)
{

    /* Sets up the pthread functionality of gcrypt
     * libssh2 doesn't do this for us so we have to do it ourselves*/
    gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);

    openlog("remote-monitor-base",LOG_PID|LOG_CONS,LOG_USER);

    syslog(LOG_DEBUG,"Starting SSH execution on rm->hostname: %s with rm->username: %s and port: %d",rm->hostname,rm->username,rm->port);

    size_t len;
    int type;

    unsigned long hostaddress;
    int sock;
    const char *fingerprint;
    int bytecount = 0;

    struct sockaddr_in sin;

    LIBSSH2_SESSION *session;
    LIBSSH2_CHANNEL *channel;
    LIBSSH2_KNOWNHOSTS *nh;

    /* results stores the output from the commands after they're executed
     * Each command  has a corresponding result so the results array is set to the same length as the commands array  */
    rm->results = malloc(rm->num_commands * sizeof(char*));
    for(int i = 0; i < rm->num_commands; i++)
        rm->results[i] = malloc(2048 * sizeof(char));

    /* Initialise libssh2 and check to see if it was initialized properly
     * libssh2_init isn't thread safe so we need to lock the thread while it executes*/
    pthread_mutex_lock(&sshinit_lock);
    int rc = libssh2_init(0);
    pthread_mutex_unlock(&sshinit_lock);
    if(rc!=0) {
        syslog(LOG_ERR,"libssh2 initilization failed");
        return 1;
    }

    /* Creates a socket connection to the specified host on the specified port */
    hostaddress = inet_addr(rm->hostname);
    sock = socket(AF_INET, SOCK_STREAM, 0);
    sin.sin_family = AF_INET;
    sin.sin_port = htons(rm->port);
    sin.sin_addr.s_addr = hostaddress;

    /* Check to see if the connection was successful */
    if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) {
        syslog(LOG_ERR,"Failed to connect to %s on port %d", rm->hostname, rm->port);
        return 1;
    }

    /* Initialise the session and check for success */
    session = libssh2_session_init();
    if(!session) {
        syslog(LOG_ERR,"Error creating session on host %s", rm->hostname);
        return 1;
    }

    /* Disable blocking for this session */
    libssh2_session_set_blocking(session,0);

    /* Start the session on the specified socket and check for success */
    while( (rc = libssh2_session_startup(session,sock)) == LIBSSH2_ERROR_EAGAIN);
    if(rc) {
        syslog(LOG_ERR,"Failure establishing SSH session %d on host %s", rc, rm->hostname);
        goto error;
    }

    /* Get the current host key and check to see if it matches with any known hosts */
    nh = libssh2_knownhost_init(session);
    if(!nh) {
        syslog(LOG_ERR,"Error while initialising known hosts collection on host %s",rm->hostname);
        goto error;
    }
    libssh2_knownhost_readfile(nh,"known_hosts",LIBSSH2_KNOWNHOST_FILE_OPENSSH);
    //libssh2_knownhost_writefile(nh,"dumpfile",LIBSSH2_KNOWNHOST_FILE_OPENSSH);
    fingerprint = libssh2_session_hostkey(session,&len,&type);

    if(fingerprint) {
        struct libssh2_knownhost *host;

        int check = libssh2_knownhost_checkp(nh,rm->hostname,rm->port,fingerprint,len
                ,LIBSSH2_KNOWNHOST_TYPE_PLAIN|LIBSSH2_KNOWNHOST_KEYENC_RAW,&host);

        if(check == LIBSSH2_KNOWNHOST_CHECK_MATCH)
            syslog(LOG_DEBUG,"Found matching host key for host %s",rm->hostname);
        else if(check == LIBSSH2_KNOWNHOST_CHECK_MISMATCH)
            syslog(LOG_ERR,"Host key was found but the key's didn't match for host %s",rm->hostname);
            //TODO Some sort of critical error will need to be generated here
        else if(check == LIBSSH2_KNOWNHOST_CHECK_NOTFOUND)
            syslog(LOG_ERR,"No host match was found for %s",rm->hostname);
            //TODO Have the ability to add the host key here
        else
            syslog(LOG_ERR,"There was a failure while attempting to match host keys for host %s",rm->hostname);
    }
    else {
        syslog(LOG_ERR,"Couldn't get host key for host: %s",rm->hostname);
        goto error;
    }

    libssh2_knownhost_free(nh);

    /* Authenticate with the specified rm->username and passwod and check for success */
    // TODO Add ability to authenticate with a private key
    if( (strlen(rm->password)) != 0 ) {
        syslog(LOG_DEBUG,"Using rm->password authentication for host %s",rm->hostname);
        while( (rc = libssh2_userauth_password(session,rm->username,rm->password)) == LIBSSH2_ERROR_EAGAIN);
        if(rc) {
            syslog(LOG_ERR,"Authentication to host %s failed",rm->hostname);
            goto error;
        }
    }
    else if( ( (strlen(rm->publickey)) != 0 ) && ( ( strlen(rm->privatekey)) != 0) ) {
        syslog(LOG_DEBUG,"Using public key authentication for host %s",rm->hostname);
        while( (rc = libssh2_userauth_publickey_fromfile(session,rm->username,rm->publickey,rm->privatekey,NULL)) == LIBSSH2_ERROR_EAGAIN);

        switch(rc) {
            case 0:
                break;
            case LIBSSH2_ERROR_AUTHENTICATION_FAILED:
                syslog(LOG_ERR,"Authentication using the supplied key for host %s was not accepted",rm->hostname);
                goto error;
            case LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED:
                syslog(LOG_ERR,"The rm->username/public key combination was invalid for host %s",rm->hostname);
                goto error;
            default:
                syslog(LOG_ERR,"Authentication to host %s failed",rm->hostname);
                goto error;
        }
    }
    
    /* Open a session for each command */
    for(int i = 0; i < rm->num_commands; i++) {

        /* Open a channel on the current channel and check for success */
        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) {
            syslog(LOG_ERR,"Error opening SSH channel on host %s",rm->hostname);
            asprintf(&(rm->results[i]),NULL);
            break;
        }

        /* Execute the command and check for success */
        while( (rc = libssh2_channel_exec(channel,rm->commands[i])) == LIBSSH2_ERROR_EAGAIN) {
            waitsocket(sock,session);
        }
        if(rc!=0) {
            syslog(LOG_ERR,"Error while executing %s in channel on host %s",rm->commands[i],rm->hostname);
            asprintf(&(rm->results[i]),NULL); 
            break;
        }

        /* Continuously read the returned stream and break once the stream has been read */
        for(;;) {
            int rc;
            do
            {
                char buffer[2048];

                rc = libssh2_channel_read(channel,buffer,sizeof(buffer));

                if(rc > 0) {
                    bytecount += rc;
                    char *output;
                    output = buffer;
                    syslog(LOG_ERR,"Got output from command %s on host %s:%s",rm->commands[i],rm->hostname,output);
                    /* Store the output in the results array */
                    asprintf(&(rm->results[i]),"%s",output);
                    memset(buffer,0,2048);
                }
            } while(rc > 0);

            if(rc == LIBSSH2_ERROR_EAGAIN) {
                waitsocket(sock,session);
            }
            else
                break;
        
        }

        /* Close the channel and check for success */
        while( (rc = libssh2_channel_close(channel)) == LIBSSH2_ERROR_EAGAIN) {
            waitsocket(sock,session);
        }
        if( (libssh2_channel_free(channel)) < 0)
            syslog(LOG_ERR,"Error while freeing channel on host %s",rm->hostname);
        channel = NULL;
    }

shutdown:

    syslog(LOG_DEBUG,"Disconnecting SSH session for host %s",rm->hostname);

    libssh2_session_disconnect(session,"Normal SSH disconnection");
    libssh2_session_free(session);

    close(sock);

    libssh2_exit();

    closelog();

    return 0;

error:

    syslog(LOG_DEBUG,"Disconnection SSH session for host %s",rm->hostname);

    libssh2_session_disconnect(session,"Normal SSH disconnection");
    libssh2_session_free(session);

    close(sock);

    libssh2_exit();

    closelog();

    return 1;
}
コード例 #29
0
bool StartLineProcessCollector::collect(MONITORING::leaseProcessStart *sample, StartLineProcessConnector *conn) {

    if (NULL == sample) {
        g_cSystemLogger.LogMessage("(%s:%s:%d):: sample is NULL \n  \n ", LOG_LOCATION);
        return false;
    }
    
    int i=0;
    ItrServerDetails  serIter;
    lineDetails ld;
    g_cSystemLogger.LogMessage("(%s:%s:%d)::cancelid %d \n ", LOG_LOCATION,sample->ip_info[i].CancelOrderId);
    if(sample->ip_info[i].CancelOrderId!=0)
    {
    char buf[50]={0};
    char recvbuf[512]={0};
    int recvLen;
    g_cSystemLogger.LogMessage("(%s:%s:%d):: size of order vector %d \n ",LOG_LOCATION,conn->orderIds.size());
    for(i=0;i<conn->orderIds.size();i++)
    {
   
	//g_cSystemLogger.LogMessage("(%s:%s(:%d)::Inside CancelOrder %d \n", LOG_LOCATION,sample->ip_info[i].CancelOrderId);
        int pos;
        int j;
	pos+=sprintf(buf+5,"%s%d%s","#",conn->orderIds[i],"#");
        g_cSystemLogger.LogMessage("(%s:%s(:%d)::order length %d buf %s \n", LOG_LOCATION,pos,buf);
        char c='0';
        for(j=0;j<=3;j++)
        {
        buf[j]=c;
	//g_cSystemLogger.LogMessage("(%s:%s(:%d)::Inside CancelOrder buf %c \n", LOG_LOCATION,buf[j]);
        }
	char p=(char)(((int)'0')+pos);
        buf[j]=p;
        g_cSystemLogger.LogMessage("(%s:%s(:%d)::Inside CancelOrder buf %s socketId %d \n", LOG_LOCATION,buf,CControllerThread::getInstance()->socketId);
        if(recvLen==write(CControllerThread::getInstance()->socketId,buf,sizeof(buf)))
        {
	   g_cSystemLogger.LogMessage("(%s:%s(:%d)::writeLen %d \n", LOG_LOCATION,recvLen);
           //CControllerThread::getInstance()->makeSocketConnection();
        }
        g_cSystemLogger.LogMessage("(%s:%s(:%d)::write sucessfull writeLen %d \n", LOG_LOCATION,recvLen);

	if(recvLen=recv(CControllerThread::getInstance()->socketId,recvbuf,sizeof(recvbuf),0)<0)
        {
	 g_cSystemLogger.LogMessage("(%s:%s(:%d)::Recv Error \n", LOG_LOCATION);
	}
	g_cSystemLogger.LogMessage("(%s:%s(:%d)::RecvLen %d recvbuf %s \n", LOG_LOCATION,recvLen,recvbuf);
        strncpy(ld.CancelOrderStatus,recvbuf,sizeof(recvbuf)); 
	CcopyStructure::copyCommandData(ld, ld.line_count);
	memset(buf,0,sizeof(buf));
        pos=0;
	sleep(1);
    }
    return true;

   }

else
{
    for(i=0;i<sample->ip_info.length();i++)
{ 
    if(strcmp(sample->ip_info[i].ipadress,"")==0)
 	break;
    LIBSSH2_CHANNEL *channel2;
    LIBSSH2_SESSION *session;
    char* userName;
    char* passWord;
    struct sockaddr_in sin;
    int rc, sock, auth_pw = 0;
    char *exitsignal = (char *) "none";
    size_t lnReturnCode;
    char command[12324] = {0};
    char processes[8024] = {0};

    char *lpUserAuthList;
    g_cSystemLogger.LogMessage("(%s:%s:%d):: Debug", LOG_LOCATION);
    rc = libssh2_init(0);
    
    strcpy(ld.ipadress,sample->ip_info[i].ipadress);
    g_cSystemLogger.LogMessage("(%s:%s:%d)::Sequence Length %d ipadress %s,and psl %s  cancelOrderId %d value of i %d \n", LOG_LOCATION, sample->ip_info._length,sample->ip_info[i].ipadress,sample->ip_info[i].psl,sample->ip_info[i].CancelOrderId,i);
    sock = socket(AF_INET, SOCK_STREAM, 0);

    sin.sin_family = AF_INET;
    sin.sin_port = htons(22);
    sin.sin_addr.s_addr = inet_addr(sample->ip_info[i].ipadress);
    if (connect(sock, (struct sockaddr*) (&sin),
            sizeof (struct sockaddr_in)) != 0) {
        g_cSystemLogger.LogMessage("(%s:%s(:%d)::failure establishing ssh", LOG_LOCATION);
        return -1;
    }

    session = libssh2_session_init();
    if (libssh2_session_handshake(session, sock)) {
        g_cSystemLogger.LogMessage("(%s:%s(:%d):: failure ssh session initiation", LOG_LOCATION);


    }
   /* if((strcmp(sample->ip_info[i].ipadress,"192.168.30.32")==0)|| (strcmp(sample->ip_info[i].psl,"192.168.30.231")==0))
    {
        userName = "******";
        passWord = "******"; 
    }
    else*/
    
         userName = "******";
         passWord = "******"; 
    
    lpUserAuthList = libssh2_userauth_list(session, userName, strlen(userName));

    if (NULL == lpUserAuthList) {
        g_cSystemLogger.LogMessage("(%s:%s(:%d):: get user auth list failed", LOG_LOCATION);

    }
    char lcPreferredAuthMethod[20] = "password";
    g_cSystemLogger.LogMessage("(%s:%s(:%d)::authentication methods(%s)", LOG_LOCATION, lpUserAuthList);
    if (strstr(lpUserAuthList, lcPreferredAuthMethod) != NULL) {
        auth_pw |= 1;
        g_cSystemLogger.LogMessage("(%s:%s(:%d)::authentication methods(%d)", LOG_LOCATION, auth_pw);
    }
    if (auth_pw & 1) {
        if (libssh2_userauth_password(session, userName, passWord)) {
            g_cSystemLogger.LogMessage("(%s:%s(:%d)::Authentation by password failed\n", LOG_LOCATION);
        }

        else {
            g_cSystemLogger.LogMessage("(%s:%s(:%d)::Authentation by mint succesded\n", LOG_LOCATION);
        }

    }

    while ((channel2 = libssh2_channel_open_session(session)) == NULL &&
            libssh2_session_last_error(session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN) {
        waitsocket(sock, session);
    }

    if (channel2 == NULL) {
        g_cSystemLogger.LogMessage("(%s:%s(:%d))ssh channel opening fail", LOG_LOCATION);
    }
   
    if(strcmp(sample->ip_info[i].psl,"Process")==0)
    {
       
    g_cSystemLogger.LogMessage("(%s:%s(:%d)) Inside Process", LOG_LOCATION);
    for(serIter=conn->getServerInfo().begin();serIter!=conn->getServerInfo().end();serIter++)
    {  
        g_cSystemLogger.LogMessage("(%s:%s(:%d)) ipadress from iter %s", LOG_LOCATION,serIter->ipAdress);
        tagServerInfo &tagServ = *serIter;
        g_cSystemLogger.LogMessage("(%s:%s(:%d)) ipadress from tagserver %s sampeip %s \n", LOG_LOCATION,tagServ.ipAdress,sample->ip_info[i].ipadress);

        if(strcmp(tagServ.ipAdress,sample->ip_info[i].ipadress)==0)
        {
            int pos=0;
            g_cSystemLogger.LogMessage("(%s:%s(:%d)) tagServ %s sample %s processLen %d \n", LOG_LOCATION,tagServ.ipAdress,sample->ip_info[i].ipadress,tagServ.noOfProcess);
            for(int j=1;j<tagServ.noOfProcess;j++)
            {
            g_cSystemLogger.LogMessage("(%s:%s(:%d)) Process %s \n", LOG_LOCATION,tagServ.processes[j].name);
            if(j==(tagServ.noOfProcess-1))
            {
            sprintf(processes+pos,tagServ.processes[j].name);
            }
            else
            {
            pos+=sprintf(processes+pos,"%s%s",tagServ.processes[j].name,"|");
          
            }
            }
            sprintf(command,"%s %s%s%s%s %s%s%s%s","ps -ef | egrep -v ","\"", "egrep|vi|tail|cat|emacs|more|nohup","\"" ,"| egrep","\"",processes,"\"","| grep -v daemon");
            g_cSystemLogger.LogMessage("(%s:%s(:%d)) command %s", LOG_LOCATION,command);
            
            while ((rc = libssh2_channel_exec(channel2, command)) == LIBSSH2_ERROR_EAGAIN) {
            waitsocket(sock, session);
            
            
        }
           lnReturnCode = libssh2_channel_read(channel2, command, sizeof (command));
           g_cSystemLogger.LogMessage("(%s:%s(:%d)) lnReturnCode %d command %s", LOG_LOCATION,lnReturnCode,command);
           strncpy(ld.processInfo,command,sizeof(command));
            memset(command, 0, sizeof (command));
            libssh2_channel_free(channel2);
            channel2 = NULL; 
        }     
    }
    }
    
    else if((strcmp(sample->ip_info[i].psl,"Space"))==0)
    {
       while ((rc = libssh2_channel_exec(channel2, "df -kh |grep -v grep")) == LIBSSH2_ERROR_EAGAIN) {
            waitsocket(sock, session);
            
        }
        lnReturnCode = libssh2_channel_read(channel2, command, sizeof (command));
        g_cSystemLogger.LogMessage("(%s:%s(:%d)lnReturnCode %d command after executing %s\n", LOG_LOCATION, lnReturnCode, command);
        strcpy(ld.spaceInfo,command);
        memset(command, 0, sizeof (command));
        libssh2_channel_free(channel2);
        channel2 = NULL;
    }
    
    else if((strcmp(sample->ip_info[i].psl,"Line"))==0)
    {
        
        DBConnection lDBConnectionObject;
        char* dbUserName = "******";
        char* dbPassWord = "******";
        char* dbName = "mani";
        char* dbPort = "5432";
        if(0==lDBConnectionObject.getFoPiQueryResult(dbUserName,dbPassWord,dbName,dbPort,sample->ip_info[i].ipadress,ld))
        {
            g_cSystemLogger.LogMessage("(%s:%s(:%d) Failed DB query \n", LOG_LOCATION);
        }
        
        g_cSystemLogger.LogMessage("(%s:%s(:%d) LineId %d Product details %s line count %d\n", LOG_LOCATION,ld.ld[0].fo_id,ld.ld[0].product_details,ld.line_count);
        lDBConnectionObject.Close();
    }
    
    
    iterMap = conn->getPath().find(sample->ip_info[i].ipadress);
    g_cSystemLogger.LogMessage("(%s:%s(:%d))Path %s \n", LOG_LOCATION,iterMap->second.c_str());

    if (sample->ip_info[i].status == true) 
    {

        sprintf(command, "%s%s",iterMap->second.c_str(),"/clear_server.sh >> /tmp/LOGS/cronlog 2>&1 &");

        while ((rc = libssh2_channel_exec(channel2, command)) == LIBSSH2_ERROR_EAGAIN) {
            waitsocket(sock, session);
        }
        lnReturnCode = libssh2_channel_read(channel2, command, sizeof (command));
        g_cSystemLogger.LogMessage("(%s:%s(:%d)lnReturnCode %d command after executing %s\n", LOG_LOCATION, lnReturnCode, command);
        memset(command, 0, sizeof (command));
        libssh2_channel_free(channel2);
        channel2 = NULL;
    }
        
    else if((sample->ip_info[i].status==false) && ((strcmp(sample->ip_info[i].psl,""))==0) && (sample->ip_info[i].CancelOrderId==0))
    {
        sprintf(command, "%s", "cd /home/mint/ga/bin; nohup ./shutdownall.sh >> /tmp/LOGS/cronlog1 2>&1 &");

        g_cSystemLogger.LogMessage("(%s:%s(:%d)%s\n", LOG_LOCATION, command);
        while ((rc = libssh2_channel_exec(channel2, command)) == LIBSSH2_ERROR_EAGAIN) {
            g_cSystemLogger.LogMessage("(%s:%s(:%d) ERROR Running command %d\n", LOG_LOCATION, rc);
            waitsocket(sock, session);
        }

        size_t lnReturnCode;
        lnReturnCode = libssh2_channel_read(channel2, command, sizeof (command));

        g_cSystemLogger.LogMessage("(%s:%s(:%d)lnReturnCode %d commandBuffer %s\n", LOG_LOCATION, lnReturnCode, command);
        memset(command, 0, sizeof (command));
        libssh2_channel_free(channel2);
        channel2 = NULL;
    }
    g_cSystemLogger.LogMessage("(%s:%s(:%d)space %s\n", LOG_LOCATION,ld.spaceInfo);
     CcopyStructure::copyCommandData(ld, ld.line_count);
    }
}
   
       
    return true;
}
コード例 #30
-1
ファイル: parser.cpp プロジェクト: alexadmin/main
QString Parser::sshRequest(QString commandline)
{
    QString host_ip(this->sharedHost);
    QString user_name=this->sharedUser;
    QString pass_word=this->sharedPass;

    //---------- connection --------------
    int libssh2_error = libssh2_init(0);
    if(libssh2_error)
    {
        qDebug("libssh2_init() error: %d", libssh2_error);
        //return -2;
    }

    QTcpSocket socket;
    socket.connectToHost(host_ip, 22);
    if(!socket.waitForConnected())
    {
        qDebug("Error connecting to host %s", host_ip.toLocal8Bit().constData());
        //return -1;
    }

    LIBSSH2_SESSION *session = libssh2_session_init();
    if(!session)
    {
        qDebug("libssh2_session_init() failed");
        //return -2;
    }

    libssh2_error = libssh2_session_startup(session, socket.socketDescriptor());
    if(libssh2_error)
    {
        qDebug("libssh2_session_startup() error: %d", libssh2_error);
        //return -3;
    }

    {
    /* At this point we havn't yet authenticated.  The first thing to do
     * is check the hostkey's fingerprint against our known hosts Your app
     * may have it hard coded, may go to a file, may present it to the
     * user, that's your call
     */
    const char *fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
    }

    libssh2_userauth_list(session, user_name.toLocal8Bit().constData(), user_name.toLocal8Bit().length());
    if(libssh2_userauth_password(
        session,
        user_name.toLocal8Bit().constData(),
        pass_word.toLocal8Bit().constData()
    ))
    {
        qDebug("Password authentication failed");

        socket.disconnectFromHost();
        libssh2_session_disconnect(session, "Client disconnecting for error");
        libssh2_session_free(session);
        libssh2_exit();

        //return -4;
    }

    // command channel
    //------------setup channel ----------------------
    LIBSSH2_CHANNEL *channel = NULL;
    channel = libssh2_channel_open_session(session);
    int rc;
    if ( channel == NULL )
    {
        qDebug()<<"Failed to open a new channel\n";
        socket.disconnectFromHost();
        //return -1;
    }
    libssh2_channel_set_blocking(channel, 1);
    while ((rc=libssh2_channel_exec(channel, commandline.toLocal8Bit().constData()))==LIBSSH2_ERROR_EAGAIN );
    if (rc)
    {
        //return -1;
    }

    //-------read channel-----------
    int read;
    QByteArray byte_array;
    byte_array.resize(4096);
    char* buffer=byte_array.data();
    int buffer_size=byte_array.size();

    QString myOutPut;

    while(true)
    {
        {
            read = libssh2_channel_read(channel, buffer, buffer_size);
            QByteArray debug = QByteArray(buffer, read);

            //qDebug()<<"STDOUT: "<<debug.constData();
            myOutPut = debug.constData();
            qDebug() << myOutPut;
            if(LIBSSH2_ERROR_EAGAIN == read)
            {
                qDebug("LIBSSH2_ERROR_EAGAIN");
                break;
            }
            else if(read  < 0)
            {
                qDebug(" error reading from channel");
                closeChannel(channel);
                goto next_channel;
            }

        }
        {
            read = libssh2_channel_read_stderr(channel, buffer, buffer_size);
            QByteArray debug = QByteArray(buffer, read);
            qDebug()<<"STDERR: "<<debug.constData();
            if(LIBSSH2_ERROR_EAGAIN == read)
            {
                qDebug("LIBSSH2_ERROR_EAGAIN");
                break;
            }
            else if(read  < 0)
            {
                qDebug(" error reading from channel");
                closeChannel(channel);
                goto next_channel;
            }

        }

        int i=0;

        i = libssh2_channel_eof(channel);
        if(i)
        {
            qDebug("libssh2_channel_eof %i", i);
            closeChannel(channel);
            goto next_channel;
        }
    }
next_channel:

    //------------ clean session
    socket.disconnectFromHost();

    libssh2_session_disconnect(session, "Client disconnecting normally");
    libssh2_session_free(session);
    libssh2_exit();

    return myOutPut;
}