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; }
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; }
int change_shell_channel_pty_size(void* ssh_session, int pty_width, int pty_heigth) { SSH_SESSION* p_session; int ec; p_session = (SSH_SESSION*)ssh_session; if(!(login_check(p_session))) { debug_log(SSH_TERMINAL_NO_SESSION_ERROR, "change_shell_channel_pty_size : no session."); return SSH_TERMINAL_NO_SESSION_ERROR; } if(p_session->session_param->channel_type != CHANNEL_TYPE_SHELL) { debug_log(SSH_TERMINAL_INVALID_CHANNEL_TYPE, "change_shell_channel_pty_size : channel type is not shell."); return SSH_TERMINAL_INVALID_CHANNEL_TYPE; } while((ec = libssh2_channel_request_pty_size(p_session->session_param->channel, pty_width, pty_heigth)) == LIBSSH2_ERROR_EAGAIN) { waitsocket(p_session->session_param->sock, p_session->session_param->session, TIMEOUT_SEC); } if(ec < 0) { debug_log(SSH_TERMINAL_CHANGE_PTY_SIZE_ERROR, "change_shell_channel_pty_size : channel request pty size failed."); return SSH_TERMINAL_CHANGE_PTY_SIZE_ERROR; } return 0; }
int ssh::quit_channel() { int rc; exitcode = 127; while( (rc = libssh2_channel_close(channel)) == LIBSSH2_ERROR_EAGAIN ) waitsocket(_sock_fd, 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; return 0; }
int close_ssh_connection(void* ssh_session) { int ec; SSH_SESSION* p_session; p_session = (SSH_SESSION*)ssh_session; if(!(login_check(p_session))) { debug_log(SSH_TERMINAL_NO_SESSION_ERROR, "close_ssh_connection : no session."); return SSH_TERMINAL_NO_SESSION_ERROR; } if(p_session->session_param->channel != NULL) { exit_thread(ssh_session); while((ec = 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); p_session->session_param->channel = NULL; } while((ec = libssh2_session_disconnect(p_session->session_param->session, "normal")) == LIBSSH2_ERROR_EAGAIN) { waitsocket(p_session->session_param->sock, p_session->session_param->session, TIMEOUT_SEC); } if(ec < 0) { debug_log(SSH_TERMINAL_SESSION_DISCONNECT_ERROR, "close_ssh_connection : disconnect failed."); return SSH_TERMINAL_SESSION_DISCONNECT_ERROR; } libssh2_session_free(p_session->session_param->session); close(p_session->session_param->sock); free(p_session->session_param); ori_thread_mutex_free(p_session->thread_param->command_queue_mutex); ori_thread_mutex_free(p_session->thread_param->add_list_mutex); ori_thread_condition_free(p_session->thread_param->command_queue_condition); ori_thread_condition_free(p_session->thread_param->add_list_condition); free(p_session->thread_param); free(p_session); return 0; }
LIBSSH2_CHANNEL *waitfor_open_channel(LIBSSH2_SESSION *session, int sock) { LIBSSH2_CHANNEL *chan = NULL; while (!(chan = libssh2_channel_open_session(session))) { int err = libssh2_session_last_error(session, NULL, NULL, 0); if (err != LIBSSH2_ERROR_EAGAIN) break; waitsocket(session, sock); } return chan; }
int open_channel_and_exec(LIBSSH2_SESSION *session, int sock, const char *cmd, char **out) { int rc; LIBSSH2_CHANNEL *chan; chan = waitfor_open_channel(session, sock); if (!chan) return -1; while ((rc = libssh2_channel_exec(chan, cmd)) == LIBSSH2_ERROR_EAGAIN) waitsocket(session, sock); if (rc != 0) return -1; rc = read_channel(chan, session, sock, out); while ((rc = libssh2_channel_close(chan)) == LIBSSH2_ERROR_EAGAIN) waitsocket(session, sock); libssh2_channel_free(chan); return 0; }
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; }
int ssh_exec_channel_open(void* ssh_session, Boolean async_mode) { SSH_SESSION* p_session; LIBSSH2_CHANNEL* channel; p_session = (SSH_SESSION*)ssh_session; if(!(login_check(p_session))) { debug_log(SSH_TERMINAL_NO_SESSION_ERROR, "ssh_exec_channel_open : no session."); return SSH_TERMINAL_NO_SESSION_ERROR; } if(p_session->session_param->channel != NULL) { debug_log(SSH_TERMINAL_ALREADY_CHANNEL_OPEN, "ssh_exec_channel_open : already channel open."); return SSH_TERMINAL_ALREADY_CHANNEL_OPEN; } 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) { debug_log(SSH_TERMINAL_CHANNEL_OPEN_ERROR, "ssh_exec_channel_open : channel open failed."); return SSH_TERMINAL_CHANNEL_OPEN_ERROR; } p_session->session_param->channel = channel; p_session->session_param->channel_type = CHANNEL_TYPE_EXEC; p_session->session_param->async_mode = async_mode; return 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; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 1; struct sockaddr_in sin; const char *fingerprint; LIBSSH2_SESSION *session; const char *username="******"; const char *password="******"; const char *loclfile="sftp_write_nonblock.c"; const char *sftppath="/tmp/sftp_write_nonblock.c"; int rc; FILE *local; LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP_HANDLE *sftp_handle; char mem[1024 * 1000]; size_t nread; size_t memuse; time_t start; long total = 0; int duration; #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2,0), &wsadata); #endif if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if (argc > 2) { username = argv[2]; } if (argc > 3) { password = argv[3]; } if (argc > 4) { loclfile = argv[4]; } if (argc > 5) { sftppath = argv[5]; } rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } local = fopen(loclfile, "rb"); if (!local) { printf("Can't local file %s\n", loclfile); return -1; } /* * The application code is responsible for creating the socket * and 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; /* Since we have set non-blocking, tell libssh2 we are 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; } /* 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 */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); printf("Fingerprint: "); for(i = 0; i < 20; i++) { printf("%02X ", (unsigned char)fingerprint[i]); } printf("\n"); if (auth_pw) { /* We could authenticate via password */ while ((rc = libssh2_userauth_password(session, username, password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { printf("Authentication by password failed.\n"); goto shutdown; } } else { /* Or by public key */ while ((rc = libssh2_userauth_publickey_fromfile(session, username, "/home/username/.ssh/id_rsa.pub", "/home/username/.ssh/id_rsa", password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { printf("\tAuthentication by public key failed\n"); goto shutdown; } } fprintf(stderr, "libssh2_sftp_init()!\n"); do { sftp_session = libssh2_sftp_init(session); if (!sftp_session && (libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN)) { fprintf(stderr, "Unable to init SFTP session\n"); goto shutdown; } } while (!sftp_session); fprintf(stderr, "libssh2_sftp_open()!\n"); /* Request a file via SFTP */ do { sftp_handle = libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_TRUNC, LIBSSH2_SFTP_S_IRUSR|LIBSSH2_SFTP_S_IWUSR| LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IROTH); if (!sftp_handle && (libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN)) { fprintf(stderr, "Unable to open file with SFTP\n"); goto shutdown; } } while (!sftp_handle); fprintf(stderr, "libssh2_sftp_open() is done, now send data!\n"); start = time(NULL); memuse = 0; /* it starts blank */ do { nread = fread(&mem[memuse], 1, sizeof(mem)-memuse, local); if (nread <= 0) { /* end of file */ if (memuse > 0) /* the previous sending is not finished */ nread = 0; else break; } memuse += nread; total += nread; /* write data in a loop until we block */ while ((rc = libssh2_sftp_write(sftp_handle, mem, memuse)) == LIBSSH2_ERROR_EAGAIN) { waitsocket(sock, session); } if(rc < 0) break; if(memuse - rc) { /* make room for more data at the end of the buffer */ memmove(&mem[0], &mem[rc], memuse - rc); memuse -= rc; } else /* 'mem' was consumed fully */ memuse = 0; } while (rc > 0); duration = (int)(time(NULL)-start); printf("%ld bytes in %d seconds makes %.1f bytes/sec\n", total, duration, total/(double)duration); fclose(local); libssh2_sftp_close(sftp_handle); libssh2_sftp_shutdown(sftp_session); shutdown: while (libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing") == LIBSSH2_ERROR_EAGAIN); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif printf("all done\n"); libssh2_exit(); return 0; }
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; }
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; }
int ssh_exec(ssh_conn_t *conn, param_t *params) { LIBSSH2_CHANNEL *channel; int rc; int exitcode = 127; char *exitsignal=(char *)"none"; const char *commandline = params->command; /* Exec non-blocking on the remove host */ while( (channel = libssh2_channel_open_session(conn->session)) == NULL && libssh2_session_last_error(conn->session,NULL,NULL,0) == LIBSSH2_ERROR_EAGAIN ) { waitsocket(conn); } if( channel == NULL ) { fprintf(stderr,"Error\n"); return ( 1 ); } rc = ssh_setenv(channel, params); if(rc<0) { if(rc==LIBSSH2_ERROR_CHANNEL_REQUEST_DENIED) printf("Error: Environment variable is not accepted by target SSH server."); goto shutdown; } while( (rc = libssh2_channel_exec(channel, commandline)) == LIBSSH2_ERROR_EAGAIN ) { waitsocket(conn); } if( rc != 0 ) { fprintf(stderr,"Error\n"); return ( 1 ); } int stream_id = 0; for( ;; ) { /* loop until we block */ int rc; do { char buffer[0x4000]; rc = libssh2_channel_read_ex( channel, stream_id, buffer, sizeof(buffer) ); if( rc > 0 ) { fwrite(buffer, sizeof(char), rc, stream_id==0?stdout:stderr); }else{ if( rc != LIBSSH2_ERROR_EAGAIN ) goto shutdown; } } while( rc > 0 ); /* this is due to blocking that would occur otherwise so we loop on this condition */ if( rc == LIBSSH2_ERROR_EAGAIN ) { waitsocket(conn); } else break; stream_id = stream_id==0?1:0; } while( (rc = libssh2_channel_close(channel)) == LIBSSH2_ERROR_EAGAIN ) waitsocket(conn); if( rc == 0 ) { exitcode = libssh2_channel_get_exit_status( channel ); libssh2_channel_get_exit_signal(channel, &exitsignal, NULL, NULL, NULL, NULL, NULL); } shutdown: libssh2_channel_free(channel); channel = NULL; return exitcode; }
RET_CODE serverConnectThread::Process(void* pcThreadParam) { CControllerThread *singleInstance; singleInstance = CControllerThread::getInstance(); iterServerInfoMap iterMap; typedef tbb::concurrent_vector<tapServerInfoMap> mapStore; typedef mapStore::iterator iterMapVector; mapStore mapStoreObj; int whileserverCount = 0; // CControllerThread *singleInstance; // singleInstance = CControllerThread::getInstance(); unsigned long long int prevSizeroot = 0; unsigned long long int currentSizeroot = 0; unsigned long long int prevSizedolat = 0; unsigned long long int currentSizedolat = 0; vector <unsigned long long int> fileSize; for(int i=0;i<10;i++) fileSize.push_back(0); char *hostAdress; const char* userName; const char* passWord; char* dbUserName; char* dbPassWord; char* dbName; char* dbPort; char* lineType; int globalCounter = 0; int count = 0; bool breakFlag; char commandBuffer[1000]; char buffer[50]; char c[20]; int lProcessListIndex, lSpaceList; FILE *p; // char *lcPreferredAuthMethod[20]; int lineCounter; DBConnection lDBConnectionObject; while (1) { count = 0; breakFlag = false; //print_micro_sec(1,stdout); for (int i=0;i<(singleInstance->serverObject.size()/3);i++) { lineCounter =0; if (IsThreadInShutdown()) { breakFlag = true; break; } tapServerInfoMap m_MapObject; tagServerInfo &tsi = singleInstance->serverObject[i]; //if(tsi.bIsDirty == false) //tsi.bIsDirty = true; //else //continue; hostAdress = tsi.ipAdress; cout <<"hostAdress1 ::: " << tsi.ipAdress << endl; userName = tsi.userName; passWord = tsi.password; dbUserName = tsi.dbUserName; dbPassWord = tsi.dbPassword; dbName = tsi.dbName; dbPort = tsi.dbPort; //cout <<"FilePath---" << tsi.Path[0].filePath << endl; //FILE *fp = fopen("LineIds.txt","w+"); //lineType = tsi.lineType; globalCounter = 0; if (!(tsi.dbconStatus)) { if (0 == lDBConnectionObject.getQueryResult(m_MapObject, dbUserName, dbPassWord, dbName, dbPort, hostAdress, lineType)) { // printf("db connection not found \n"); /* for (std::map <long,std::string>::iterator iterMap = m_MapObject.begin(); iterMap != m_MapObject.end(); iterMap++) { fprintf(fp,"\n"); fprintf(fp,"%ld",(*iterMap).first); }*/ } for (std::map <long,std::string>::iterator iterMap = m_MapObject.begin(); iterMap != m_MapObject.end(); iterMap++) { //cout << "userIds::" << iterMap->second << endl; //cout << "first::" << iterMap->first << endl; conn->orderIds.push_back(iterMap->first); } //std::cout<<"m_MapObject"<<m_MapObject.size()<<endl; mapStoreObj.push_back(m_MapObject); lDBConnectionObject.Close(); tsi.dbconStatus = true; } //memset(buffer,'\0',sizeof(buffer)); //commandBuffer[1000] = {0}; // buffer[50] = {0}; // c[20] = {0}; char *lpUserAuthList; struct sockaddr_in sin; int rc, sock, auth_pw = 0; lProcessListIndex, lSpaceList = 1; sprintf(buffer, "ping -c 3 %s | grep -c %s", tsi.ipAdress, "\"3 received\""); g_cSystemLogger.LogMessage("(%s:%s:%d)::Ping Buffer %s", LOG_LOCATION,buffer); p = popen(buffer, "r"); fgets(c, 10, p); //cout << "ping Commmand buff" << buffer << endl; // cout <<" C " << c << endl; //pclose(p); g_cSystemLogger.LogMessage("(%s:%s:%d)::If Ping Output %s", LOG_LOCATION,c); if (atoi(c) == 1) { tsi.serverstatus = true; } else { usleep(1000); p = popen(buffer,"r"); fgets(c,10,p); pclose(p); g_cSystemLogger.LogMessage("(%s:%s:%d)::Else Ping Output %s", LOG_LOCATION,c); cout << "Else C" << c << endl; if(atoi(c) == 1) { tsi.serverstatus = true; } else { tsi.serverstatus = false; CcopyStructure::copyData(tsi,0,0,0); continue; } } memset(buffer,'\0',sizeof(buffer)); memset(c,'\0',sizeof(c)); rc = libssh2_init(0); if (rc != 0) { g_cSystemLogger.LogMessage("(%s:%s:%d)::failure establishing ssh", LOG_LOCATION); return 1; } if (tsi.serverstatus == true && tsi.conectstatus == false) { sock = socket(AF_INET, SOCK_STREAM, 0); tsi.m_socketId = sock; sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = inet_addr(tsi.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, tsi.m_socketId)) { return -1; } tsi.session = session; lpUserAuthList = libssh2_userauth_list(session, userName, strlen(userName)); if (NULL == lpUserAuthList) { g_cSystemLogger.LogMessage("(%s:%s(:%d):: get user auth list failed", LOG_LOCATION); continue; } 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); } g_cSystemLogger.LogMessage("(%s:%s(:%d)::after auth_pw 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 password succeded\n", LOG_LOCATION); } } tsi.session = session; tsi.conectstatus = true; } tapServerInfoMap &MapObject = mapStoreObj.at(count++); if (strcmp(tsi.lineType, "FO") == 0) { int i=0; for (iterMap = MapObject.begin(); iterMap != MapObject.end(); iterMap++) { while (((channel = libssh2_channel_open_session(tsi.session)) == NULL) && (libssh2_session_last_error(tsi.session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN)) { waitsocket(sock, tsi.session); } if (channel == NULL) { g_cSystemLogger.LogMessage("(%s:%s(:%d))ssh channel opening fail",LOG_LOCATION); // goto shutdown; } sprintf(commandBuffer, "%s %s%s%s%d%s%s%s", "/bin/netstat -n|/bin/grep -c", "\"", iterMap->second.c_str(), ":", 9602, ".*", "ESTABLISHED", "\""); while ((rc = libssh2_channel_exec(channel, commandBuffer)) == LIBSSH2_ERROR_EAGAIN) { waitsocket(sock, tsi.session); } int lnReturnCode; lnReturnCode = libssh2_channel_read(channel, commandBuffer, sizeof (commandBuffer)); g_cSystemLogger.LogMessage("(%s:%s(:%d))::commandBuffer %s lnreturncode %d\n", LOG_LOCATION,commandBuffer,lnReturnCode); //std::cout<<"iterMap->first" <<iterMap->first <<endl; if (commandBuffer[0] == '1') { strncpy(tsi.lineInfo[i].ipv4adresss, iterMap->second.c_str(), 16); tsi.lineInfo[i].ipv4adresss[16] = '\0'; tsi.lineInfo[i].status = TRUE; tsi.lineInfo[i].userId = iterMap->first; } else if (commandBuffer[0] == '0') { strncpy(tsi.lineInfo[i].ipv4adresss, iterMap->second.c_str(), 16); tsi.lineInfo[i].ipv4adresss[16] = '\0'; tsi.lineInfo[i].status = FALSE; tsi.lineInfo[i].userId = iterMap->first; } //std::cout<<"tsi.lineInfo[lineCounter].userId" <<tsi.lineInfo[lineCounter].userId <<endl; //std::cout<<"tsi.lineInfo[lineCounter].status" <<tsi.lineInfo[lineCounter].status <<endl; if (LIBSSH2_ERROR_EAGAIN == lnReturnCode) { waitsocket(sock, tsi.session); } i++; memset(commandBuffer, 0, sizeof (commandBuffer)); libssh2_channel_free(channel); channel = NULL; } //globalCounter = lineCounter; } /* if (strcmp(tsi.lineType, "CM") == 0) { int lineCounter = 0; for (iterMap = MapObject.begin(); iterMap != MapObject.end(); iterMap++) { while (((channel = libssh2_channel_open_session(tsi.session)) == NULL) && (libssh2_session_last_error(tsi.session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN)) { waitsocket(sock, tsi.session); } if (channel == NULL) { g_cSystemLogger.LogMessage("(%s:%s(:%d))ssh channel opening fail",LOG_LOCATION); // goto shutdown; } sprintf(commandBuffer, "%s %s%s%s%d%s%s%s", "/bin/netstat -n|/bin/grep -c", "\"", iterMap->second.c_str(), ":", 9601, ".*", "ESTABLISHED", "\""); g_cSystemLogger.LogMessage("(%s:%s(:%d))::command for netstat %s\n", LOG_LOCATION, commandBuffer); while ((rc = libssh2_channel_exec(channel, commandBuffer)) == LIBSSH2_ERROR_EAGAIN) { waitsocket(sock, tsi.session); } int lnReturnCode; lnReturnCode = libssh2_channel_read(channel, commandBuffer, sizeof (commandBuffer)); if (commandBuffer[0] == '1') { strncpy(tsi.lineInfo[lineCounter].ipv4adresss, iterMap->second.c_str(), 16); tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0'; tsi.lineInfo[lineCounter].status = TRUE; tsi.lineInfo[lineCounter].userId = iterMap->first; } else if (commandBuffer[0] == '0') { strncpy(tsi.lineInfo[lineCounter].ipv4adresss, iterMap->second.c_str(), 16); tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0'; tsi.lineInfo[lineCounter].status = FALSE; tsi.lineInfo[lineCounter].userId = iterMap->first; } if (LIBSSH2_ERROR_EAGAIN == lnReturnCode) { waitsocket(sock, tsi.session); } lineCounter++; memset(commandBuffer, 0, sizeof (commandBuffer)); libssh2_channel_free(channel);elOrderI channel = NULL; } globalCounter = lineCounter; } */ // for(int i=1;i<tsi.noOfFilePath;i++) // { // printf("Inside Filesizecheck \n"); // cout <<"filePath::::" << tsi.Path[0].filePath << endl; if (!(strcmp(tsi.Path[0].filePath,"") == 0)) { while (((channel = libssh2_channel_open_session(tsi.session)) == NULL) && (libssh2_session_last_error(tsi.session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN)) { waitsocket(sock, tsi.session); } if (channel == NULL) { g_cSystemLogger.LogMessage("(%s:%s(:%d))ssh channel opening fail",LOG_LOCATION); // goto shutdown; } sprintf(commandBuffer,"%s %s %s", "du -b",tsi.Path[0].filePath,"| awk '{print $1}' "); g_cSystemLogger.LogMessage("(%s:%s(:%d))::command for netstat %s\n", LOG_LOCATION, commandBuffer); while ((rc = libssh2_channel_exec(channel, commandBuffer)) == LIBSSH2_ERROR_EAGAIN) { waitsocket(sock, tsi.session); } size_t lnReturnCode; lnReturnCode = libssh2_channel_read(channel, commandBuffer, sizeof (commandBuffer)); char buff[30]; int j=0; int i=0; while(commandBuffer[j]!='\n') { buff[i]=commandBuffer[j]; j++; i++; lnReturnCode--; } lnReturnCode--; currentSizeroot = (atoi(buff)); if(lnReturnCode) { i=0; j++; memset(buff,0,sizeof(buff)); while(commandBuffer[j]!='\n') { buff[i]=commandBuffer[j]; j++; i++; lnReturnCode--; } } currentSizedolat = (atoi(buff)); //cout <<"currentSizeroot" << currentSizeroot <<" "<<fileSize[0] <<endl; //cout <<"currentSizedolat" << currentSizedolat <<" " <<fileSize[1] <<endl; if(currentSizeroot!=currentSizedolat) { if((currentSizeroot-fileSize[0])>0 && (currentSizedolat-fileSize[1])>0) { tsi.Path[0].status=true; } else { tsi.Path[0].status=false; } fileSize.insert(fileSize.begin()+0,currentSizeroot); fileSize.insert(fileSize.begin()+1,currentSizedolat); } else { if((currentSizeroot-fileSize[2])>0) { tsi.Path[0].status=true; } else { tsi.Path[0].status=false; } fileSize.insert(fileSize.begin()+2,currentSizeroot); } memset(commandBuffer, 0, sizeof (commandBuffer)); libssh2_channel_free(channel); channel = NULL; // } } /* std::cout<<"tsi.lineType"<<tsi.lineType<<endl; if (strcmp(tsi.lineType, "ColoBridge") == 0) { singleInstance g_cSystemLogger.LogMessage("(%s:%s(:%d))::Inside ColoBridge \n", LOG_LOCATION); memset(tsi.lineType, 0, sizeof (tsi.lineType)); strcpy(tsi.lineType,"CM"); std::cout<<"LineType"<<tsi.lineType<<endl; int lineCounter = 0; while (((channel = libssh2_channel_open_session(tsi.session)) == NULL) && (libssh2_session_last_error(tsi.session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN)) { waitsocket(sock, tsi.session); } if (channel == NULL) { g_cSystemLogger.LogMessage("(%s:%s(:%d))ssh channel opening fail",LOG_LOCATION); // goto shutdown; } sprintf(commandBuffer, "%s %s%s%s%d%s%s%s", "/bin/netstat -n|/bin/grep -c", "\"", "192.168.30.32", ":", 2004, ".*", "ESTABLISHED", "\""); g_cSystemLogger.LogMessage("(%s:%s(:%d))::command for netstat %s\n", LOG_LOCATION, commandBuffer); while ((rc = libssh2_channel_exec(channel, commandBuffer)) == LIBSSH2_ERROR_EAGAIN) { waitsocket(sock, tsi.session); } int lnReturnCode; lnReturnCode = libssh2_channel_read(channel, commandBuffer, sizeof (commandBuffer)); if (commandBuffer[0] == '1') { tsi.lineInfo[lineCounter].userId=2004; strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.32", 16); tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0'; tsi.lineInfo[lineCounter].userId=2004; tsi.lineInfo[lineCounter].status = TRUE; } else if (commandBuffer[0] == '0') { strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.32", 16); tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0'; tsi.lineInfo[lineCounter].userId=2004; tsi.lineInfo[lineCounter].status = FALSE; } if (LIBSSH2_ERROR_EAGAIN == lnReturnCode) { waitsocket(sock, tsi.session); } lineCounter++; memset(commandBuffer, 0, sizeof (commandBuffer)); libssh2_channel_free(channel); channel = NULL; while (((channel = libssh2_channel_open_session(tsi.session)) == NULL) && (libssh2_session_last_error(tsi.session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN)) { waitsocket(sock, tsi.session); } if (channel == NULL) { g_cSystemLogger.LogMessage("(%s:%s(:%d))ssh channel opening fail",LOG_LOCATION); // goto shutdown; } sprintf(commandBuffer, "%s %s%s%s%d%s%s%s", "/bin/netstat -n|/bin/grep -c", "\"", "192.168.30.32", ":", 2005, ".*", "ESTABLISHED", "\""); g_cSystemLogger.LogMessage("(%s:%s(:%d))::command for netstat %s\n", LOG_LOCATION, commandBuffer); while ((rc = libssh2_channel_exec(channel, commandBuffer)) == LIBSSH2_ERROR_EAGAIN) { waitsocket(sock, tsi.session); } lnReturnCode; lnReturnCode = libssh2_channel_read(channel, commandBuffer, sizeof (commandBuffer)); if (commandBuffer[0] == '1') { strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.32", 16); tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0'; tsi.lineInfo[lineCounter].userId=2005; tsi.lineInfo[lineCounter].status = TRUE; } else if (commandBuffer[0] == '0') { strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.32", 16); tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0'; tsi.lineInfo[lineCounter].userId=2005; tsi.lineInfo[lineCounter].status = FALSE; } if (LIBSSH2_ERROR_EAGAIN == lnReturnCode) { waitsocket(sock, tsi.session); } lineCounter++; memset(commandBuffer, 0, sizeof (commandBuffer)); libssh2_channel_free(channel); channel = NULL; singleInstance->serverObject.size() while (((channel = libssh2_channel_open_session(tsi.session)) == NULL) && (libssh2_session_last_error(tsi.session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN)) { waitsocket(sock, tsi.session); } if (channel == NULL) { g_cSystemLogger.LogMessage("(%s:%s(:%d))ssh channel opening fail",LOG_LOCATION); // goto shutdown; } sprintf(commandBuffer, "%s %s%s%s%d%s%s%s", "/bin/netstat -n|/bin/grep -c", "\"", "192.168.30.32", ":", 5432, ".*", "ESTABLISHED", "\""); g_cSystemLogger.LogMessage("(%s:%s(:%d))::command for netstat %s\n", LOG_LOCATION, commandBuffer); while ((rc = libssh2_channel_exec(channel, commandBuffer)) == LIBSSH2_ERROR_EAGAIN) { waitsocket(sock, tsi.session); } lnReturnCode; lnReturnCode = libssh2_channel_read(channel, commandBuffer, sizeof (commandBuffer)); if (commandBuffer[0] == '2') { strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.32", 16); tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0'; tsi.lineInfo[lineCounter].userId=5432; tsi.lineInfo[lineCounter].status = TRUE; } else if (commandBuffer[0] == '0') { strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.32", 16); tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0'; tsi.lineInfo[lineCounter].userId=5432; tsi.lineInfo[lineCounter].status = FALSE; } if (LIBSSH2_ERROR_EAGAIN == lnReturnCode) { waitsocket(sock, tsi.session); } lineCounter++; memset(commandBuffer, 0, sizeof (commandBuffer)); libssh2_channel_free(channel); channel = NULL; while (((channel = libssh2_channel_open_session(tsi.session)) == NULL) && (libssh2_session_last_error(tsi.session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN)) { waitsocket(sock, tsi.session); } if (channel == NULL) { g_cSystemLogger.LogMessage("(%s:%s(:%d))ssh channel opening fail",LOG_LOCATION); // goto shutdown; } sprintf(commandBuffer, "%s %s%s%s%d%s%s%s", "/bin/netstat -n|/bin/grep -c", "\"", "192.168.30.231", ":", 2004, ".*", "ESTABLISHED", "\""); singleInstance->serverObject.size() g_cSystemLogger.LogMessage("(%s:%s(:%d))::command for netstat %s\n", LOG_LOCATION, commandBuffer); while ((rc = libssh2_channel_exec(channel, commandBuffer)) == LIBSSH2_ERROR_EAGAIN) { waitsocket(sock, tsi.session); } lnReturnCode; lnReturnCode = libssh2_channel_read(channel, commandBuffer, sizeof (commandBuffer)); if (commandBuffer[0] == '1') { strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.231", 16); tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0'; tsi.lineInfo[lineCounter].userId=2004; tsi.lineInfo[lineCounter].status = TRUE; } else if (commandBuffer[0] == '0') { strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.231", 16); tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0'; tsi.lineInfo[lineCounter].userId=2004; tsi.lineInfo[lineCounter].status = FALSE; } if (LIBSSH2_ERROR_EAGAIN == lnReturnCode) { waitsocket(sock, tsi.session); } lineCounter++; memset(commandBuffer, 0, sizeof (commandBuffer)); libssh2_channel_free(channel); channel = NULL; while (((channel = libssh2_channel_open_session(tsi.session)) == NULL) && (libssh2_session_last_error(tsi.session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN)) { waitsocket(sock, tsi.session); } if (channel == NULL) { g_cSystemLogger.LogMessage("(%s:%s(:%d))ssh channel opening fail",LOG_LOCATION); // goto shutdown; } sprintf(commandBuffer, "%s %s%s%s%d%s%s%s", "/bin/netstat -n|/bin/grep -c", "\"", "192.168.30.231", ":", 2005, ".*", "ESTABLISHED", "\""); g_cSystemLogger.LogMessage("(%s:%s(:%d))::command for netstat %s\n", LOG_LOCATION, commandBuffer); while ((rc = libssh2_channel_exec(channel, commandBuffer)) == LIBSSH2_ERROR_EAGAIN) { waitsocket(sock, tsi.session); } lnReturnCode; lnReturnCode = libssh2_channel_read(channel, commandBuffer, sizeof (commandBuffer)); if (commandBuffer[0] == '1') { strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.231", 16); tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0'; tsi.lineInfo[lineCounter].userId=2005; tsi.lineInfo[lineCounter].status = TRUE; } else if (commandBuffer[0] == '0') { strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.231", 16); tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0'; tsi.lineInfo[lineCounter].userId=2005; tsi.lineInfo[lineCounter].status = FALSE; } if (LIBSSH2_ERROR_EAGAIN == lnReturnCode) { waitsocket(sock, tsi.session); } lineCounter++; memset(commandBuffer, 0, sizeof (commandBuffer)); libssh2_channel_free(channel); channel = NULL; while (((channel = libssh2_channel_open_session(tsi.session)) == NULL) && (libssh2_session_last_error(tsi.session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN)) { waitsocket(sock, tsi.session); } if (channel == NULL) { g_cSystemLogger.LogMessage("(%s:%s(:%d))ssh channel opening fail",LOG_LOCATION); // goto shutdown; } sprintf(commandBuffer, "%s %s%s%s%d%s%s%s", "/bin/netstat -n|/bin/grep -c", "\"", "192.168.30.231", ":", 5432, ".*", "ESTABLISHED", "\""); g_cSystemLogger.LogMessage("(%s:%s(:%d))::command for netstat %s\n", LOG_LOCATION, commandBuffer); while ((rc = libssh2_channel_exec(channel, commandBuffer)) == LIBSSH2_ERROR_EAGAIN) { waitsocket(sock, tsi.session); } lnReturnCode; lnReturnCode = libssh2_channel_read(channel, commandBuffer, sizeof (commandBuffer)); //std::cout<<"lnReturnCode"<<lnReturnCode<<endl; if (commandBuffer[0] == '2') { strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.231", 16); tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0'; tsi.lineInfo[lineCounter].userId=5432; tsi.lineInfo[lineCounter].status = TRUE; } else if (commandBuffer[0] == '0') { strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.231", 16); tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0'; tsi.lineInfo[lineCounter].userId=5432; tsi.lineInfo[lineCounter].status = FALSE; } if (LIBSSH2_ERROR_EAGAIN == lnReturnCode) { waitsocket(sock, tsi.session); } lineCounter++; memset(commandBuffer, 0, sizeof (commandBuffer)); libssh2_channel_free(channel); channel = NULL; globalCounter = lineCounter; }*/ for (lProcessListIndex = 1; lProcessListIndex < tsi.noOfProcess; lProcessListIndex++) { g_cSystemLogger.LogMessage("(%s:%s(:%d))::process name\n", LOG_LOCATION); while ((channel = libssh2_channel_open_session(tsi.session)) == NULL && libssh2_session_last_error(tsi.session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN) { waitsocket(sock, tsi.session); } if (channel == NULL) { fprintf(stderr, "failure establishing ssh"); //goto shutdown; } sprintf(commandBuffer, "%s %s", "pidof -s", tsi.processes[lProcessListIndex].name); g_cSystemLogger.LogMessage("(%s:%s(:%d)):: Pid of process command %s\n", LOG_LOCATION, commandBuffer); while ((rc = libssh2_channel_exec(channel, commandBuffer)) == LIBSSH2_ERROR_EAGAIN) { waitsocket(sock, tsi.session); } size_t lnReturnCode; lnReturnCode = libssh2_channel_read(channel, commandBuffer, sizeof (commandBuffer)); g_cSystemLogger.LogMessage("(%s:%s(:%d))::commandBuffer %s lnreturncode %d\n", LOG_LOCATION,commandBuffer,lnReturnCode); if (lnReturnCode == 0) { tsi.processes[lProcessListIndex].process_on_off = FALSE; } else { tsi.processes[lProcessListIndex].process_on_off = TRUE; if (lnReturnCode != LIBSSH2_ERROR_EAGAIN) { g_cSystemLogger.LogMessage("(%s:%s(:%d))::libbssh2 %d\n", LOG_LOCATION, lnReturnCode); } } if (LIBSSH2_ERROR_EAGAIN == lnReturnCode) { waitsocket(sock, tsi.session); } g_cSystemLogger.LogMessage("(%s:%s(:%d))::tsi.processes[i].process_on_off %d \n", LOG_LOCATION, tsi.processes[lProcessListIndex].process_on_off); memset(commandBuffer, 0, sizeof (commandBuffer)); if (channel) { libssh2_channel_free(channel); channel = NULL; } } char percnt[5] = "\"%\""; for (lSpaceList = 1; lSpaceList < tsi.noOfSpace; lSpaceList++) { while ((channel = libssh2_channel_open_session(tsi.session)) == NULL && libssh2_session_last_error(tsi.session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN) { waitsocket(sock, tsi.session); } if (channel == NULL) { g_cSystemLogger.LogMessage("failure establishing ssh"); } sprintf(commandBuffer, "%s %s %s %s %s", "df -hk | grep", tsi.space[lSpaceList].name, "| awk '{print $(NF-1)}' | awk -F", percnt, "'{print $1}'"); g_cSystemLogger.LogMessage("(%s:%s(:%d))::command for space%s\n", LOG_LOCATION, commandBuffer); while ((rc = libssh2_channel_exec(channel, commandBuffer)) == LIBSSH2_ERROR_EAGAIN) { waitsocket(sock, tsi.session); } int lnReturnCode; lnReturnCode = libssh2_channel_read(channel, commandBuffer, sizeof (commandBuffer)); if (lnReturnCode >= 0) { if (atoi(commandBuffer) > 90) { tsi.space[lSpaceList].space_full = TRUE; } else { tsi.space[lSpaceList].space_full = FALSE; } } if (LIBSSH2_ERROR_EAGAIN == lnReturnCode) { waitsocket(sock, tsi.session); } memset(commandBuffer, 0, sizeof (commandBuffer)); if (channel) { libssh2_channel_free(channel); channel = NULL; } } CcopyStructure::copyData(tsi, tsi.noOfProcess, tsi.noOfSpace, tsi.noOfLine); } // whileserverCount++; //std::cout << "while count" << whileserverCount << endl; ///if(!(singleInstance->is_connected(singleInstance->socketId))) //singleInstance->makeSocketConnection(); if (breakFlag) { break; } } for (int i=0;i<(singleInstance->serverObject.size()/3);i++) { tagServerInfo tsi; tsi = (singleInstance->serverObject[i]); libssh2_session_disconnect(tsi.session, "Shutting down,thank you"); libssh2_session_free(tsi.session); close(tsi.m_socketId); libssh2_exit(); } return 1; }
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; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 1; struct sockaddr_in sin; const char *fingerprint; LIBSSH2_SESSION *session; LIBSSH2_CHANNEL *channel; const char *username="******"; const char *password="******"; const char *scppath="/tmp/TEST"; libssh2_struct_stat fileinfo; #ifdef HAVE_GETTIMEOFDAY struct timeval start; struct timeval end; long time_ms; #endif int rc; int spin = 0; libssh2_struct_stat_size got = 0; libssh2_struct_stat_size total = 0; #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) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if (argc > 2) { username = argv[2]; } if (argc > 3) { password = argv[3]; } if (argc > 4) { scppath = argv[4]; } rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } /* 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; /* Since we have set non-blocking, tell libssh2 we are non-blocking */ libssh2_session_set_blocking(session, 0); #ifdef HAVE_GETTIMEOFDAY gettimeofday(&start, NULL); #endif /* ... 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; } /* 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 */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); fprintf(stderr, "Fingerprint: "); for(i = 0; i < 20; i++) { fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]); } fprintf(stderr, "\n"); if (auth_pw) { /* 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/username/" ".ssh/id_rsa.pub", "/home/username/" ".ssh/id_rsa", password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "\tAuthentication by public key failed\n"); goto shutdown; } } #if 0 libssh2_trace(session, LIBSSH2_TRACE_CONN); #endif /* Request a file via SCP */ fprintf(stderr, "libssh2_scp_recv2()!\n"); do { channel = libssh2_scp_recv2(session, scppath, &fileinfo); if (!channel) { if(libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) { char *err_msg; libssh2_session_last_error(session, &err_msg, NULL, 0); fprintf(stderr, "%s\n", err_msg); goto shutdown; } else { fprintf(stderr, "libssh2_scp_recv() spin\n"); waitsocket(sock, session); } } } while (!channel); fprintf(stderr, "libssh2_scp_recv() is done, now receive data!\n"); while(got < fileinfo.st_size) { char mem[1024*24]; int rc; do { int amount=sizeof(mem); if ((fileinfo.st_size -got) < amount) { amount = (int)(fileinfo.st_size - got); } /* loop until we block */ rc = libssh2_channel_read(channel, mem, amount); if (rc > 0) { write(1, mem, rc); got += rc; total += rc; } } while (rc > 0); if ((rc == LIBSSH2_ERROR_EAGAIN) && (got < fileinfo.st_size)) { /* this is due to blocking that would occur otherwise so we loop on this condition */ spin++; waitsocket(sock, session); /* now we wait */ continue; } break; } #ifdef HAVE_GETTIMEOFDAY gettimeofday(&end, NULL); time_ms = tvdiff(end, start); fprintf(stderr, "Got " LIBSSH2_STRUCT_STAT_SIZE_FORMAT " bytes in %ld ms = %.1f bytes/sec spin: %d\n", total, time_ms, total/(time_ms/1000.0), spin); #else fprintf(stderr, "Got " LIBSSH2_STRUCT_STAT_SIZE_FORMAT " bytes spin: %d\n", total, spin); #endif 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; }
void Exec::run() { qDebug() << "SecureConnection::Exec::run " << m_command; // Exececute non-blocking on the remote host libssh2_session_set_blocking(m_session, 0); LIBSSH2_CHANNEL *channel; while ( (channel = libssh2_channel_open_session(m_session)) == 0 && libssh2_session_last_error(m_session, 0, 0, 0) == LIBSSH2_ERROR_EAGAIN) { waitsocket(); } if (channel == 0) throw Exception("Failed to open exec channel"); int rc(0); QByteArray cmd(m_command.toLocal8Bit()); while ( (rc = libssh2_channel_exec(channel, cmd.data())) == LIBSSH2_ERROR_EAGAIN) { waitsocket(); } std::string output; int bytecount(0); if (rc == 0) { for ( ; ; ) { // loop until we block int bc; char buffer[0x400]; do { bc = libssh2_channel_read(channel, buffer, sizeof(buffer)); if (bc > 0) { output.append(buffer, bc); bytecount += bc; } //qDebug() <<" sleeping 5"; sleep(5); } while( bc > 0 && !m_terminate); if (m_terminate) break; // this is due to blocking that would occur // otherwise so we loop on this condition if (bc == LIBSSH2_ERROR_EAGAIN) { waitsocket(); }else { break; } } }else { m_errorMessage = "Failed to execute command: " + m_command; } while ( (rc = libssh2_channel_close(channel)) == LIBSSH2_ERROR_EAGAIN ) { waitsocket(); } if (!m_terminate) { char *exitsignal=(char *)"none"; if (rc == 0) { libssh2_channel_get_exit_signal(channel, &exitsignal, 0, 0, 0, 0, 0); } if (exitsignal) { m_errorMessage += "\nClose on channel received signal " + QString(exitsignal); } } libssh2_channel_free(channel); if (!m_errorMessage.isEmpty()) throw Exception(m_errorMessage); if (!m_terminate) m_outputMessage = QString::fromStdString(output).trimmed(); qDebug() << " return:" << m_outputMessage; }
int ssh::exec_cmd(const string &command) { int rc; /* 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_fd, session); } if( channel == NULL ) { cout << "Error" << std::endl; exit( 1 ); } while( (rc = libssh2_channel_exec(channel, command.c_str())) == LIBSSH2_ERROR_EAGAIN ) { waitsocket(_sock_fd, session); } if( rc != 0 ) { cout << "Error" << std::endl; 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;*/ /* cout << "We read: " << std::endl;*/ cout << "[" << _ip_addr << "]====start====== " << std::endl; /*for( i=0; i < rc; ++i ) fputc( buffer[i], stderr);*/ cout << buffer; cout << "[" << _ip_addr << "]====end======== " << std::endl; } /*else { if( rc != LIBSSH2_ERROR_EAGAIN ) no need to output this for the EAGAIN case cout << "libssh2_channel_read returned " << rc << std::endl; }*/ } while( rc > 0 ); do { char buffer2[0x4000]; rc = libssh2_channel_read_stderr( channel, buffer2, sizeof(buffer2) ); if( rc > 0 ) { /* int i; bytecount += rc;*/ /*cout << "We read: " << std::endl;*/ cout << "[" << _ip_addr << "]====start====== " << std::endl; /*for( i=0; i < rc; ++i ) fputc( buffer[i], stderr);*/ cout << buffer2; cout << "[" << _ip_addr << "]====end======== " << std::endl; } /*else { if( rc != LIBSSH2_ERROR_EAGAIN ) no need to output this for the EAGAIN case cout << "libssh2_channel_read_stderr returned " << rc << std::endl; }*/ } 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_fd, session); } else break; } quit_channel(); return 0; }
int ssh_shell_channel_open(void* ssh_session) { SSH_SESSION* p_session; LIBSSH2_CHANNEL* channel; int ec; p_session = (SSH_SESSION*)ssh_session; if(!(login_check(p_session))) { debug_log(SSH_TERMINAL_NO_SESSION_ERROR, "ssh_shell_channel_open : no session."); return SSH_TERMINAL_NO_SESSION_ERROR; } if(p_session->session_param->channel != NULL) { debug_log(SSH_TERMINAL_ALREADY_CHANNEL_OPEN, "ssh_shell_channel_open : already channel open."); return SSH_TERMINAL_ALREADY_CHANNEL_OPEN; } 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) { debug_log(SSH_TERMINAL_CHANNEL_OPEN_ERROR, "ssh_shell_channel_open : channel open failed."); return SSH_TERMINAL_CHANNEL_OPEN_ERROR; } while((ec = libssh2_channel_request_pty(channel, "vt100")) == LIBSSH2_ERROR_EAGAIN) { waitsocket(p_session->session_param->sock, p_session->session_param->session, TIMEOUT_SEC);; } if(ec < 0){ debug_log(SSH_TERMINAL_REQUEST_PTY_ERROR, "ssh_shell_channel_open : request pty failed."); while(libssh2_channel_close(channel) == LIBSSH2_ERROR_EAGAIN) { waitsocket(p_session->session_param->sock, p_session->session_param->session, TIMEOUT_SEC); } libssh2_channel_free(channel); return SSH_TERMINAL_REQUEST_PTY_ERROR; } while((ec = libssh2_channel_request_pty_size(channel, DEFAULT_PTY_SIZE_WIDTH, DEFAULT_PTY_SIZE_HEIGHT)) == LIBSSH2_ERROR_EAGAIN) { waitsocket(p_session->session_param->sock, p_session->session_param->session, TIMEOUT_SEC); } if(ec < 0){ debug_log(SSH_TERMINAL_REQUEST_PTY_ERROR, "ssh_shell_channel_open : request pty failed."); while(libssh2_channel_close(channel) == LIBSSH2_ERROR_EAGAIN) { waitsocket(p_session->session_param->sock, p_session->session_param->session, TIMEOUT_SEC); } libssh2_channel_free(channel); return SSH_TERMINAL_REQUEST_PTY_ERROR; } while((ec = libssh2_channel_shell(channel)) == LIBSSH2_ERROR_EAGAIN) { waitsocket(p_session->session_param->sock, p_session->session_param->session, TIMEOUT_SEC); } if(ec < 0) { debug_log(SSH_TERMINAL_SHELL_ERROR, "ssh_shell_channel_open : channel shell failed."); while(libssh2_channel_close(channel) == LIBSSH2_ERROR_EAGAIN) { waitsocket(p_session->session_param->sock, p_session->session_param->session, TIMEOUT_SEC); } libssh2_channel_free(channel); return SSH_TERMINAL_SHELL_ERROR; } p_session->session_param->channel = channel; p_session->session_param->channel_type = CHANNEL_TYPE_SHELL; return 0; }
//获取此分站范围内的设备IP std::string CEasyssh::GetDeviceMAC(void) { if (m_bIsErr) { //自动重连 ConnectAP(); return std::string("Error"); } std::string str_ip_pool = ""; char *exitsignal=(char *)"none"; int rc = 0; const char *commandline = "/usr/www/wstalist ath0"; /* Exec non-blocking on the remove host */ LIBSSH2_CHANNEL *channel; while( (channel = libssh2_channel_open_session(m_ssh_session)) == NULL && libssh2_session_last_error(m_ssh_session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN) { waitsocket(m_sock, m_ssh_session); } if(channel == NULL) { TRACE(_T("libssh2_channel_open_session Error\n")); return std::string("Error"); } while( (rc = libssh2_channel_exec(channel, commandline)) == LIBSSH2_ERROR_EAGAIN) { waitsocket(m_sock, m_ssh_session); } if(rc != 0) { return std::string("Error"); } for( ;; ) { /* loop until we block */ int rc; do { char buffer[0x4000]; rc = libssh2_channel_read(channel, buffer, sizeof(buffer)); if(rc > 0) { std::string str_temp(buffer, 0, rc); str_ip_pool += str_temp; } } while( rc > 0 ); /* this is due to blocking that would occur otherwise so we loop on this condition */ if( rc == LIBSSH2_ERROR_EAGAIN ) { waitsocket(m_sock, m_ssh_session); } else break; } while( (rc = libssh2_channel_close(channel)) == LIBSSH2_ERROR_EAGAIN ) waitsocket(m_sock, m_ssh_session); if( rc == 0 ) { libssh2_channel_get_exit_status(channel); libssh2_channel_get_exit_signal(channel, &exitsignal, NULL, NULL, NULL, NULL, NULL); } libssh2_channel_free(channel); channel = NULL; return str_ip_pool; }
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; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 1; struct sockaddr_in sin; const char *fingerprint; LIBSSH2_SESSION *session = NULL; LIBSSH2_CHANNEL *channel; const char *username="******"; const char *password="******"; const char *loclfile="scp_write.c"; const char *scppath="/tmp/TEST"; FILE *local; int rc; char mem[1024*100]; size_t nread; char *ptr; struct stat fileinfo; time_t start; long total = 0; int duration; size_t prev; #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2,0), &wsadata); #endif if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if (argc > 2) { username = argv[2]; } if (argc > 3) { password = argv[3]; } if(argc > 4) { loclfile = argv[4]; } if (argc > 5) { scppath = argv[5]; } rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } local = fopen(loclfile, "rb"); if (!local) { fprintf(stderr, "Can't local file %s\n", loclfile); return -1; } stat(loclfile, &fileinfo); /* 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; /* Since we have set non-blocking, tell libssh2 we are 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; } /* 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 */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); fprintf(stderr, "Fingerprint: "); for(i = 0; i < 20; i++) { fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]); } fprintf(stderr, "\n"); if (auth_pw) { /* 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/username/.ssh/id_rsa.pub", "/home/username/.ssh/id_rsa", password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "\tAuthentication by public key failed\n"); goto shutdown; } } /* Send a file via scp. The mode parameter must only have permissions! */ do { channel = libssh2_scp_send(session, scppath, fileinfo.st_mode & 0777, (unsigned long)fileinfo.st_size); if ((!channel) && (libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN)) { char *err_msg; libssh2_session_last_error(session, &err_msg, NULL, 0); fprintf(stderr, "%s\n", err_msg); goto shutdown; } } while (!channel); fprintf(stderr, "SCP session waiting to send file\n"); start = time(NULL); do { nread = fread(mem, 1, sizeof(mem), local); if (nread <= 0) { /* end of file */ break; } ptr = mem; total += nread; prev = 0; do { while ((rc = libssh2_channel_write(channel, ptr, nread)) == LIBSSH2_ERROR_EAGAIN) { waitsocket(sock, session); prev = 0; } if (rc < 0) { fprintf(stderr, "ERROR %d total %ld / %d prev %d\n", rc, total, (int)nread, (int)prev); break; } else { prev = nread; /* rc indicates how many bytes were written this time */ nread -= rc; ptr += rc; } } while (nread); } while (!nread); /* only continue if nread was drained */ duration = (int)(time(NULL)-start); printf("%ld bytes in %d seconds makes %.1f bytes/sec\n", total, duration, total/(double)duration); fprintf(stderr, "Sending EOF\n"); while (libssh2_channel_send_eof(channel) == LIBSSH2_ERROR_EAGAIN); fprintf(stderr, "Waiting for EOF\n"); while (libssh2_channel_wait_eof(channel) == LIBSSH2_ERROR_EAGAIN); fprintf(stderr, "Waiting for channel to close\n"); while (libssh2_channel_wait_closed(channel) == LIBSSH2_ERROR_EAGAIN); libssh2_channel_free(channel); channel = NULL; shutdown: while (libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing") == LIBSSH2_ERROR_EAGAIN); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif fprintf(stderr, "all done\n"); libssh2_exit(); return 0; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 1; struct sockaddr_in sin; const char *fingerprint; LIBSSH2_SESSION *session; const char *username="******"; const char *password="******"; const char *sftppath="/tmp/TEST"; struct timeval start; struct timeval end; int rc; int total = 0; long time_ms; int spin = 0; #if defined(HAVE_IOCTLSOCKET) long flag = 1; #endif LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP_HANDLE *sftp_handle; #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2,0), &wsadata); #endif if (argc > 1) { hostaddr = inet_addr(argv[1]); } else { hostaddr = htonl(0x7F000001); } if (argc > 2) { username = argv[2]; } if (argc > 3) { password = argv[3]; } if (argc > 4) { sftppath = argv[4]; } rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } /* * The application code is responsible for creating the socket * and 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; /* Since we have set non-blocking, tell libssh2 we are non-blocking */ libssh2_session_set_blocking(session, 0); gettimeofday(&start, NULL); /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ while ((rc = libssh2_session_startup(session, sock)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "Failure establishing SSH session: %d\n", rc); return -1; } /* 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 */ fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); fprintf(stderr, "Fingerprint: "); for(i = 0; i < 20; i++) { fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]); } fprintf(stderr, "\n"); if (auth_pw) { /* 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/username/" ".ssh/id_rsa.pub", "/home/username/" ".ssh/id_rsa", password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { fprintf(stderr, "\tAuthentication by public key failed\n"); goto shutdown; } } #if 0 libssh2_trace(session, LIBSSH2_TRACE_CONN); #endif fprintf(stderr, "libssh2_sftp_init()!\n"); do { sftp_session = libssh2_sftp_init(session); if(!sftp_session) { if(libssh2_session_last_errno(session) == LIBSSH2_ERROR_EAGAIN) { fprintf(stderr, "non-blocking init\n"); waitsocket(sock, session); /* now we wait */ } else { fprintf(stderr, "Unable to init SFTP session\n"); goto shutdown; } } } while (!sftp_session); fprintf(stderr, "libssh2_sftp_open()!\n"); /* Request a file via SFTP */ do { sftp_handle = libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_READ, 0); if (!sftp_handle) { if (libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) { fprintf(stderr, "Unable to open file with SFTP\n"); goto shutdown; } else { fprintf(stderr, "non-blocking open\n"); waitsocket(sock, session); /* now we wait */ } } } while (!sftp_handle); fprintf(stderr, "libssh2_sftp_open() is done, now receive data!\n"); do { char mem[1024*24]; /* loop until we fail */ while ((rc = libssh2_sftp_read(sftp_handle, mem, sizeof(mem))) == LIBSSH2_ERROR_EAGAIN) { spin++; waitsocket(sock, session); /* now we wait */ } if (rc > 0) { total += rc; write(1, mem, rc); } else { break; } } while (1); gettimeofday(&end, NULL); time_ms = tvdiff(end, start); printf("Got %d bytes in %ld ms = %.1f bytes/sec spin: %d\n", total, time_ms, total/(time_ms/1000.0), spin ); libssh2_sftp_close(sftp_handle); libssh2_sftp_shutdown(sftp_session); shutdown: printf("libssh2_session_disconnect\n"); while (libssh2_session_disconnect(session, "Normal Shutdown, Thank you") == LIBSSH2_ERROR_EAGAIN); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif fprintf(stderr, "all done\n"); libssh2_exit(); return 0; }
int oph_ssh_submit(const char *cmd) { int sock; struct sockaddr_in sin; struct addrinfo hints, *result; LIBSSH2_SESSION *session; LIBSSH2_CHANNEL *channel; int rc; int exitcode; char *exitsignal = (char *) "none"; int bytecount = 0; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = 0; hints.ai_protocol = 0; result = NULL; rc = getaddrinfo(oph_ip_target_host, NULL, &hints, &result); if (rc != 0) { pmesg_safe(&global_flag, LOG_ERROR, __FILE__, __LINE__, "Unable to resolve address from target hostname: %s\n", gai_strerror(rc)); return OPH_LIBSSH_ERROR; } sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = ((struct sockaddr_in *) result->ai_addr)->sin_addr.s_addr; freeaddrinfo(result); if (connect(sock, (struct sockaddr *) (&sin), sizeof(struct sockaddr_in)) != 0) { #ifdef WIN32 closesocket(sock); #else close(sock); #endif pmesg_safe(&global_flag, LOG_ERROR, __FILE__, __LINE__, "Failed to connect to submission host\n"); return OPH_LIBSSH_ERROR; } pthread_mutex_lock(&libssh2_flag); // Lock the access to SSH library pmesg_safe(&global_flag, LOG_DEBUG, __FILE__, __LINE__, "SSH2 library locked\n"); rc = libssh2_init(0); if (rc != 0) { #ifdef WIN32 closesocket(sock); #else close(sock); #endif pthread_mutex_unlock(&libssh2_flag); pmesg_safe(&global_flag, LOG_ERROR, __FILE__, __LINE__, "libssh2 initialization failed (%d)\n", rc); return OPH_LIBSSH_ERROR; } session = libssh2_session_init(); if (!session) { #ifdef WIN32 closesocket(sock); #else close(sock); #endif libssh2_exit(); pthread_mutex_unlock(&libssh2_flag); pmesg_safe(&global_flag, LOG_ERROR, __FILE__, __LINE__, "Failed to init ssh sessione\n"); return OPH_LIBSSH_ERROR; } libssh2_session_set_blocking(session, 0); while ((rc = libssh2_session_handshake(session, sock)) == LIBSSH2_ERROR_EAGAIN); if (rc) { libssh2_session_disconnect(session, "Session disconnected"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif libssh2_exit(); pthread_mutex_unlock(&libssh2_flag); pmesg_safe(&global_flag, LOG_ERROR, __FILE__, __LINE__, "Failure establishing SSH session: %d\n", rc); return OPH_LIBSSH_ERROR; } while ((rc = libssh2_userauth_publickey_fromfile(session, oph_subm_user, oph_subm_user_publk, oph_subm_user_privk, "")) == LIBSSH2_ERROR_EAGAIN); if (rc) { libssh2_session_disconnect(session, "Session disconnected"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif libssh2_exit(); pthread_mutex_unlock(&libssh2_flag); pmesg_safe(&global_flag, LOG_ERROR, __FILE__, __LINE__, "Authentication by public key failed\n"); return OPH_LIBSSH_ERROR; } 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) { libssh2_session_disconnect(session, "Session disconnected"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif libssh2_exit(); pthread_mutex_unlock(&libssh2_flag); pmesg_safe(&global_flag, LOG_ERROR, __FILE__, __LINE__, "Error during opening session channel\n"); return OPH_LIBSSH_ERROR; } while ((rc = libssh2_channel_exec(channel, cmd)) == LIBSSH2_ERROR_EAGAIN) { waitsocket(sock, session); } if (rc != 0) { libssh2_channel_free(channel); libssh2_session_disconnect(session, "Session disconnected"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif libssh2_exit(); pthread_mutex_unlock(&libssh2_flag); pmesg_safe(&global_flag, LOG_ERROR, __FILE__, __LINE__, "Error during opening session channel\n"); return OPH_LIBSSH_ERROR; } int flag = 0; for (;;) { int rc; do { char buffer[0x4000]; rc = libssh2_channel_read(channel, buffer, sizeof(buffer)); if (rc > 0) { int i; bytecount += rc; if (!flag) { pmesg_safe(&global_flag, LOG_DEBUG, __FILE__, __LINE__, "ssh submission returned:\n"); flag = 1; } for (i = 0; i < rc; ++i) pmesg_safe(&global_flag, LOG_DEBUG, __FILE__, __LINE__, "%c\n", buffer[i]); } else if (rc != LIBSSH2_ERROR_EAGAIN) pmesg_safe(&global_flag, LOG_DEBUG, __FILE__, __LINE__, "ssh channel read returned %d\n", rc); } while (rc > 0); 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) pmesg_safe(&global_flag, LOG_DEBUG, __FILE__, __LINE__, "ssh got signal %s\n", exitsignal); else pmesg_safe(&global_flag, LOG_DEBUG, __FILE__, __LINE__, "ssh exit code %d with: bytecount %d\n", exitcode, bytecount); libssh2_channel_free(channel); channel = NULL; libssh2_session_disconnect(session, "Session ended normally"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif pmesg_safe(&global_flag, LOG_DEBUG, __FILE__, __LINE__, "Session ended normally\n"); libssh2_exit(); pthread_mutex_unlock(&libssh2_flag); // Release the lock for SSH library pmesg_safe(&global_flag, LOG_DEBUG, __FILE__, __LINE__, "SSH2 library unlocked\n"); return OPH_LIBSSH_OK; }