int main(int argc, char *argv[]) { int rc, i, auth = AUTH_NONE; struct sockaddr_in sin; socklen_t sinlen = sizeof(sin); const char *fingerprint; char *userauthlist; LIBSSH2_SESSION *session; LIBSSH2_LISTENER *listener = NULL; LIBSSH2_CHANNEL *channel = NULL; fd_set fds; struct timeval tv; ssize_t len, wr; char buf[16384]; #ifdef WIN32 SOCKET sock = INVALID_SOCKET, forwardsock = INVALID_SOCKET; WSADATA wsadata; int err; err = WSAStartup(MAKEWORD(2,0), &wsadata); if (err != 0) { fprintf(stderr, "WSAStartup failed with error: %d\n", err); return 1; } #else int sock = -1, forwardsock = -1; #endif if (argc > 1) server_ip = argv[1]; if (argc > 2) username = argv[2]; if (argc > 3) password = argv[3]; if (argc > 4) remote_listenhost = argv[4]; if (argc > 5) remote_wantport = atoi(argv[5]); if (argc > 6) local_destip = argv[6]; if (argc > 7) local_destport = atoi(argv[7]); rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } /* Connect to SSH server */ sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); #ifdef WIN32 if (sock == INVALID_SOCKET) { fprintf(stderr, "failed to open socket!\n"); return -1; } #else if (sock == -1) { perror("socket"); return -1; } #endif sin.sin_family = AF_INET; if (INADDR_NONE == (sin.sin_addr.s_addr = inet_addr(server_ip))) { perror("inet_addr"); return -1; } sin.sin_port = htons(22); 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) { fprintf(stderr, "Could not initialize SSH session!\n"); return -1; } /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_handshake(session, sock); if(rc) { fprintf(stderr, "Error when starting up 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"); /* check what authentication methods are available */ userauthlist = libssh2_userauth_list(session, username, strlen(username)); fprintf(stderr, "Authentication methods: %s\n", userauthlist); if (strstr(userauthlist, "password")) auth |= AUTH_PASSWORD; if (strstr(userauthlist, "publickey")) auth |= AUTH_PUBLICKEY; /* check for options */ if(argc > 8) { if ((auth & AUTH_PASSWORD) && !strcasecmp(argv[8], "-p")) auth = AUTH_PASSWORD; if ((auth & AUTH_PUBLICKEY) && !strcasecmp(argv[8], "-k")) auth = AUTH_PUBLICKEY; } if (auth & AUTH_PASSWORD) { if (libssh2_userauth_password(session, username, password)) { fprintf(stderr, "Authentication by password failed.\n"); goto shutdown; } } else if (auth & AUTH_PUBLICKEY) { if (libssh2_userauth_publickey_fromfile(session, username, keyfile1, keyfile2, password)) { fprintf(stderr, "\tAuthentication by public key failed!\n"); goto shutdown; } fprintf(stderr, "\tAuthentication by public key succeeded.\n"); } else { fprintf(stderr, "No supported authentication methods found!\n"); goto shutdown; } fprintf(stderr, "Asking server to listen on remote %s:%d\n", remote_listenhost, remote_wantport); listener = libssh2_channel_forward_listen_ex(session, remote_listenhost, remote_wantport, &remote_listenport, 1); if (!listener) { fprintf(stderr, "Could not start the tcpip-forward listener!\n" "(Note that this can be a problem at the server!" " Please review the server logs.)\n"); goto shutdown; } fprintf(stderr, "Server is listening on %s:%d\n", remote_listenhost, remote_listenport); fprintf(stderr, "Waiting for remote connection\n"); channel = libssh2_channel_forward_accept(listener); if (!channel) { fprintf(stderr, "Could not accept connection!\n" "(Note that this can be a problem at the server!" " Please review the server logs.)\n"); goto shutdown; } fprintf(stderr, "Accepted remote connection. Connecting to local server %s:%d\n", local_destip, local_destport); forwardsock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); #ifdef WIN32 if (forwardsock == INVALID_SOCKET) { fprintf(stderr, "failed to open forward socket!\n"); goto shutdown; } #else if (forwardsock == -1) { perror("socket"); goto shutdown; } #endif sin.sin_family = AF_INET; sin.sin_port = htons(local_destport); if (INADDR_NONE == (sin.sin_addr.s_addr = inet_addr(local_destip))) { perror("inet_addr"); goto shutdown; } if (-1 == connect(forwardsock, (struct sockaddr *)&sin, sinlen)) { perror("connect"); goto shutdown; } fprintf(stderr, "Forwarding connection from remote %s:%d to local %s:%d\n", remote_listenhost, remote_listenport, local_destip, local_destport); /* Must use non-blocking IO hereafter due to the current libssh2 API */ libssh2_session_set_blocking(session, 0); while (1) { FD_ZERO(&fds); FD_SET(forwardsock, &fds); tv.tv_sec = 0; tv.tv_usec = 100000; rc = select(forwardsock + 1, &fds, NULL, NULL, &tv); if (-1 == rc) { perror("select"); goto shutdown; } if (rc && FD_ISSET(forwardsock, &fds)) { len = recv(forwardsock, buf, sizeof(buf), 0); if (len < 0) { perror("read"); goto shutdown; } else if (0 == len) { fprintf(stderr, "The local server at %s:%d disconnected!\n", local_destip, local_destport); goto shutdown; } wr = 0; do { i = libssh2_channel_write(channel, buf, len); if (i < 0) { fprintf(stderr, "libssh2_channel_write: %d\n", i); goto shutdown; } wr += i; } while(i > 0 && wr < len); } while (1) { len = libssh2_channel_read(channel, buf, sizeof(buf)); if (LIBSSH2_ERROR_EAGAIN == len) break; else if (len < 0) { fprintf(stderr, "libssh2_channel_read: %d", (int)len); goto shutdown; } wr = 0; while (wr < len) { i = send(forwardsock, buf + wr, len - wr, 0); if (i <= 0) { perror("write"); goto shutdown; } wr += i; } if (libssh2_channel_eof(channel)) { fprintf(stderr, "The remote client at %s:%d disconnected!\n", remote_listenhost, remote_listenport); goto shutdown; } } } shutdown: #ifdef WIN32 closesocket(forwardsock); #else close(forwardsock); #endif if (channel) libssh2_channel_free(channel); if (listener) libssh2_channel_forward_cancel(listener); libssh2_session_disconnect(session, "Client disconnecting normally"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif libssh2_exit(); return 0; }
int ssh2_forward_port(const char *hostip, const char *username, const char *password, int listenport, const char *desthost, int destport, int *initialized, int *finished, char **errmsg) { int rc, sock = -1, listensock = -1, forwardsock = -1, i; struct sockaddr_in sin; socklen_t sinlen; LIBSSH2_SESSION *session; LIBSSH2_CHANNEL *channel = NULL; const char *shost; unsigned int sport; fd_set fds; struct timeval tv; ssize_t len, wr; char buf[16384]; struct StringBuffer *sberrmsg = new_string_buffer(); #ifdef WIN32 char sockopt; WSADATA wsadata; WSAStartup(MAKEWORD(2,0), &wsadata); #else int sockopt; #endif rc = libssh2_init (0); if (rc != 0) { sbprintf (sberrmsg, "libssh2 initialization failed (%d)\n", rc); return 1; } /* Connect to SSH server */ sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; if (INADDR_NONE == (sin.sin_addr.s_addr = inet_addr(hostip))) { perror("inet_addr"); return -1; } sin.sin_port = htons(22); if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { sbprintf(sberrmsg, "failed to connect!\n"); return -1; } /* Create a session instance */ session = libssh2_session_init(); if(!session) { sbprintf(sberrmsg, "Could not initialize SSH session!\n"); return -1; } /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_handshake(session, sock); if(rc) { sbprintf(sberrmsg, "Error when starting up SSH session: %d\n", rc); return -1; } if (libssh2_userauth_password(session, username, password)) { sbprintf(sberrmsg, "Authentication by password failed.\n"); goto shutdown; } listensock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); sin.sin_family = AF_INET; sin.sin_port = htons(listenport); if (INADDR_NONE == (sin.sin_addr.s_addr = inet_addr("127.0.0.1"))) { sbprintf(sberrmsg, "inet_addr: %s.", strerror(errno)); goto shutdown; } sockopt = 1; setsockopt(listensock, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(sockopt)); sinlen=sizeof(sin); if (-1 == bind(listensock, (struct sockaddr *)&sin, sinlen)) { sbprintf(sberrmsg, "bind: %s.", strerror(errno)); goto shutdown; } if (-1 == listen(listensock, 2)) { sbprintf(sberrmsg, "listen: %s.", strerror(errno)); goto shutdown; } printf("Waiting for TCP connection on %s:%d...\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port)); *initialized = 1; forwardsock = accept(listensock, (struct sockaddr *)&sin, &sinlen); if (-1 == forwardsock) { sbprintf(sberrmsg, "accept: %s.", strerror(errno)); goto shutdown; } shost = inet_ntoa(sin.sin_addr); sport = ntohs(sin.sin_port); printf("Forwarding connection from %s:%d here to remote %s:%d\n", shost, sport, desthost, destport); channel = libssh2_channel_direct_tcpip_ex(session, desthost, destport, shost, sport); if (!channel) { sbprintf(sberrmsg, "Could not open the direct-tcpip channel!\n" "(Note that this can be a problem at the server!" " Please review the server logs.)\n"); goto shutdown; } /* Must use non-blocking IO hereafter due to the current libssh2 API */ libssh2_session_set_blocking(session, 0); while (1) { if(*finished) libssh2_channel_send_eof(channel); FD_ZERO(&fds); FD_SET(forwardsock, &fds); tv.tv_sec = 0; tv.tv_usec = 100000; rc = select(forwardsock + 1, &fds, NULL, NULL, &tv); if (-1 == rc) { sbprintf(sberrmsg, "select: %s.", strerror(errno)); goto shutdown; } if (rc && FD_ISSET(forwardsock, &fds)) { len = recv(forwardsock, buf, sizeof(buf), 0); if (len < 0) { perror("read"); goto shutdown; } else if (0 == len) { printf("The client at %s:%d disconnected!\n", shost, sport); goto shutdown; } wr = 0; do { i = libssh2_channel_write(channel, buf, len); if (i < 0) { sbprintf(sberrmsg, "libssh2_channel_write: %d\n", i); goto shutdown; } wr += i; } while(i > 0 && wr < len); } while (1) { len = libssh2_channel_read(channel, buf, sizeof(buf)); if (LIBSSH2_ERROR_EAGAIN == len) break; else if (len < 0) { sbprintf(sberrmsg, "libssh2_channel_read: %d", (int)len); goto shutdown; } wr = 0; while (wr < len) { i = send(forwardsock, buf + wr, len - wr, 0); if (i <= 0) { perror("write"); goto shutdown; } wr += i; } if (libssh2_channel_eof(channel)) { printf("The server at %s:%d disconnected!\n", desthost, destport); goto shutdown; } } } shutdown: fprintf(stderr, "finished = %d\n", *finished); #ifdef WIN32 closesocket(forwardsock); closesocket(listensock); #else close(forwardsock); close(listensock); #endif if (channel) libssh2_channel_free(channel); libssh2_session_disconnect(session, "Client disconnecting normally"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif libssh2_exit(); if(string_buffer_is_empty(sberrmsg)) { free_string_buffer(sberrmsg, 1); return 0; } *errmsg = free_string_buffer(sberrmsg, 0); return 1; }
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"; #ifdef HAVE_GETTIMEOFDAY struct timeval start; struct timeval end; long time_ms; #endif int rc; int total = 0; int spin = 0; LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP_HANDLE *sftp_handle; #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) { 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); #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 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); #ifdef HAVE_GETTIMEOFDAY gettimeofday(&end, NULL); time_ms = tvdiff(end, start); fprintf(stderr, "Got %d bytes in %ld ms = %.1f bytes/sec spin: %d\n", total, time_ms, total/(time_ms/1000.0), spin ); #else fprintf(stderr, "Got %d bytes spin: %d\n", total, spin); #endif libssh2_sftp_close(sftp_handle); libssh2_sftp_shutdown(sftp_session); shutdown: fprintf(stderr, "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 main(int argc, char *argv[]) { unsigned long hostaddr; int sock, i, auth_pw = 0; struct sockaddr_in sin; const char *fingerprint; char *userauthlist; LIBSSH2_SESSION *session; int rc; 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 blocking */ libssh2_session_set_blocking(session, 1); /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_startup(session, sock); 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"); /* check what authentication methods are available */ userauthlist = libssh2_userauth_list(session, username, strlen(username)); printf("Authentication methods: %s\n", userauthlist); if (strstr(userauthlist, "password") != NULL) { auth_pw |= 1; } if (strstr(userauthlist, "keyboard-interactive") != NULL) { auth_pw |= 2; } if (strstr(userauthlist, "publickey") != NULL) { auth_pw |= 4; } /* if we got an 4. argument we set this option if supported */ if(argc > 5) { if ((auth_pw & 1) && !strcasecmp(argv[5], "-p")) { auth_pw = 1; } if ((auth_pw & 2) && !strcasecmp(argv[5], "-i")) { auth_pw = 2; } if ((auth_pw & 4) && !strcasecmp(argv[5], "-k")) { auth_pw = 4; } } if (auth_pw & 1) { /* We could authenticate via password */ if (libssh2_userauth_password(session, username, password)) { fprintf(stderr, "Authentication by password failed.\n"); goto shutdown; } } else if (auth_pw & 2) { /* Or via keyboard-interactive */ if (libssh2_userauth_keyboard_interactive(session, username, &kbd_callback) ) { printf("\tAuthentication by keyboard-interactive failed!\n"); goto shutdown; } else { printf("\tAuthentication by keyboard-interactive succeeded.\n"); } } else if (auth_pw & 4) { /* Or by public key */ if (libssh2_userauth_publickey_fromfile(session, username, keyfile1, keyfile2, password)) { printf("\tAuthentication by public key failed!\n"); goto shutdown; } else { printf("\tAuthentication by public key succeeded.\n"); } } else { printf("No supported authentication methods found!\n"); goto shutdown; } fprintf(stderr, "libssh2_sftp_init()!\n"); sftp_session = libssh2_sftp_init(session); if (!sftp_session) { fprintf(stderr, "Unable to init SFTP session\n"); goto shutdown; } fprintf(stderr, "libssh2_sftp_open()!\n"); /* Request a file via SFTP */ sftp_handle = libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_READ, 0); if (!sftp_handle) { fprintf(stderr, "Unable to open file with SFTP: %ld\n", libssh2_sftp_last_error(sftp_session)); goto shutdown; } fprintf(stderr, "libssh2_sftp_open() is done, now receive data!\n"); do { char mem[1024]; /* loop until we fail */ fprintf(stderr, "libssh2_sftp_read()!\n"); rc = libssh2_sftp_read(sftp_handle, mem, sizeof(mem)); if (rc > 0) { write(1, mem, rc); } else { break; } } while (1); libssh2_sftp_close(sftp_handle); libssh2_sftp_shutdown(sftp_session); 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 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/sftp_mkdir_nonblock"; int rc; #if defined(HAVE_IOCTLSOCKET) long flag = 1; #endif LIBSSH2_SFTP *sftp_session; #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; /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_startup(session, sock); 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 */ if (libssh2_userauth_password(session, username, password)) { printf("Authentication by password failed.\n"); goto shutdown; } } else { /* Or by public key */ if (libssh2_userauth_publickey_fromfile(session, username, "/home/username/.ssh/id_rsa.pub", "/home/username/.ssh/id_rsa", password)) { printf("\tAuthentication by public key failed\n"); goto shutdown; } } fprintf(stderr, "libssh2_sftp_init()!\n"); sftp_session = libssh2_sftp_init(session); if (!sftp_session) { fprintf(stderr, "Unable to init SFTP session\n"); goto shutdown; } /* Since we have set non-blocking, tell libssh2 we are non-blocking */ libssh2_session_set_blocking(session, 0); fprintf(stderr, "libssh2_sftp_mkdirnb()!\n"); /* Make a directory via SFTP */ while (libssh2_sftp_mkdir(sftp_session, sftppath, LIBSSH2_SFTP_S_IRWXU| LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IXGRP| LIBSSH2_SFTP_S_IROTH|LIBSSH2_SFTP_S_IXOTH) == LIBSSH2_ERROR_EAGAIN); libssh2_sftp_shutdown(sftp_session); shutdown: libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif printf("all done\n"); libssh2_exit(); return 0; }
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; WSAStartup(MAKEWORD(2,0), &wsadata); #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) printf("\nGot signal: %s\n", exitsignal); else printf("\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 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"; struct stat fileinfo; int rc; off_t got=0; #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) { 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; /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_startup(session, sock); 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 */ if (libssh2_userauth_password(session, username, password)) { fprintf(stderr, "Authentication by password failed.\n"); goto shutdown; } } else { /* Or by public key */ if (libssh2_userauth_publickey_fromfile(session, username, "/home/username/.ssh/id_rsa.pub", "/home/username/.ssh/id_rsa", password)) { fprintf(stderr, "\tAuthentication by public key failed\n"); goto shutdown; } } /* Request a file via SCP */ channel = libssh2_scp_recv(session, scppath, &fileinfo); if (!channel) { fprintf(stderr, "Unable to open a session: %d\n", libssh2_session_last_errno(session)); goto shutdown; } while(got < fileinfo.st_size) { char mem[1024]; int amount=sizeof(mem); if((fileinfo.st_size -got) < amount) { amount = fileinfo.st_size -got; } rc = libssh2_channel_read(channel, mem, amount); if(rc > 0) { write(1, mem, rc); } else if(rc < 0) { fprintf(stderr, "libssh2_channel_read() failed: %d\n", rc); break; } got += rc; } 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; }
/* * call-seq: * Native.exit -> true * * Exits libssh2, deallocating any memory used internally. If this is called * Native.init must be called prior to doing anything with libssh2 again. * * */ static VALUE libexit(VALUE module) { libssh2_exit(); return Qtrue; }
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; }
int main(int argc, char *argv[]) { int rc, i, auth = AUTH_NONE; struct sockaddr_in sin; const char *fingerprint; char *userauthlist; LIBSSH2_SESSION *session; LIBSSH2_CHANNEL *channel = NULL; char buf[1048576]; /* avoid any buffer reallocation for simplicity */ ssize_t len; #ifdef WIN32 SOCKET sock = INVALID_SOCKET; WSADATA wsadata; int err; err = WSAStartup(MAKEWORD(2,0), &wsadata); if (err != 0) { fprintf(stderr, "WSAStartup failed with error: %d\n", err); return 1; } #else int sock = -1; #endif if (argc > 1) server_ip = argv[1]; if (argc > 2) username = argv[2]; if (argc > 3) password = argv[3]; rc = libssh2_init (0); if (rc != 0) { fprintf (stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } /* Connect to SSH server */ sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); #ifdef WIN32 if (sock == INVALID_SOCKET) { fprintf(stderr, "failed to open socket!\n"); return -1; } #else if (sock == -1) { perror("socket"); return -1; } #endif sin.sin_family = AF_INET; if (INADDR_NONE == (sin.sin_addr.s_addr = inet_addr(server_ip))) { fprintf(stderr, "inet_addr: Invalid IP address \"%s\"\n", server_ip); return -1; } sin.sin_port = htons(830); if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { fprintf(stderr, "Failed to connect to %s!\n", inet_ntoa(sin.sin_addr)); return -1; } /* Create a session instance */ session = libssh2_session_init(); if(!session) { fprintf(stderr, "Could not initialize SSH session!\n"); return -1; } /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_handshake(session, sock); if(rc) { fprintf(stderr, "Error when starting up 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"); /* check what authentication methods are available */ userauthlist = libssh2_userauth_list(session, username, strlen(username)); fprintf(stderr, "Authentication methods: %s\n", userauthlist); if (strstr(userauthlist, "password")) auth |= AUTH_PASSWORD; if (strstr(userauthlist, "publickey")) auth |= AUTH_PUBLICKEY; /* check for options */ if(argc > 4) { if ((auth & AUTH_PASSWORD) && !strcasecmp(argv[4], "-p")) auth = AUTH_PASSWORD; if ((auth & AUTH_PUBLICKEY) && !strcasecmp(argv[4], "-k")) auth = AUTH_PUBLICKEY; } if (auth & AUTH_PASSWORD) { if (libssh2_userauth_password(session, username, password)) { fprintf(stderr, "Authentication by password failed.\n"); goto shutdown; } } else if (auth & AUTH_PUBLICKEY) { if (libssh2_userauth_publickey_fromfile(session, username, keyfile1, keyfile2, password)) { fprintf(stderr, "Authentication by public key failed!\n"); goto shutdown; } fprintf(stderr, "Authentication by public key succeeded.\n"); } else { fprintf(stderr, "No supported authentication methods found!\n"); goto shutdown; } /* open a channel */ channel = libssh2_channel_open_session(session); if (!channel) { fprintf(stderr, "Could not open the channel!\n" "(Note that this can be a problem at the server!" " Please review the server logs.)\n"); goto shutdown; } /* execute the subsystem on our channel */ if (libssh2_channel_subsystem(channel, "netconf")) { fprintf(stderr, "Could not execute the \"netconf\" subsystem!\n" "(Note that this can be a problem at the server!" " Please review the server logs.)\n"); goto shutdown; } /* NETCONF: http://tools.ietf.org/html/draft-ietf-netconf-ssh-06 */ fprintf(stderr, "Sending NETCONF client <hello>\n"); snprintf(buf, sizeof(buf), "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<hello>" "<capabilities>" "<capability>urn:ietf:params:xml:ns:netconf:base:1.0</capability>" "</capabilities>" "</hello>\n" "]]>]]>\n%n", (int *)&len); if (-1 == netconf_write(channel, buf, len)) goto shutdown; fprintf(stderr, "Reading NETCONF server <hello>\n"); len = netconf_read_until(channel, "</hello>", buf, sizeof(buf)); if (-1 == len) goto shutdown; fprintf(stderr, "Got %d bytes:\n----------------------\n%s", (int)len, buf); fprintf(stderr, "Sending NETCONF <rpc>\n"); snprintf(buf, sizeof(buf), "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" "<get-interface-information><terse/></get-interface-information>" "</rpc>\n" "]]>]]>\n%n", (int *)&len); if (-1 == netconf_write(channel, buf, len)) goto shutdown; fprintf(stderr, "Reading NETCONF <rpc-reply>\n"); len = netconf_read_until(channel, "</rpc-reply>", buf, sizeof(buf)); if (-1 == len) goto shutdown; fprintf(stderr, "Got %d bytes:\n----------------------\n%s", (int)len, buf); shutdown: if (channel) libssh2_channel_free(channel); libssh2_session_disconnect(session, "Client disconnecting normally"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif libssh2_exit(); return 0; }
SSH2Utils::~SSH2Utils(void) { libssh2_exit(); }
//Uses ssh to transfer a data file. //I took most of this code from the example file scp_write.c in the libssh2 examples. //!!!! This could really be generalized... !!!! int SendFilesTo51(char* loclfile,char* serverlocation) { int error_code = 0; #if defined(HAVE_LIBSSH2) char filename[1024]; if(FindFilename(loclfile,filename)) { printf("Error: Bad filename for hydrograph file. (%s)\n",loclfile); return 1; } char scppath[1024]; sprintf(scppath,"%s/%s",serverlocation,filename); //sprintf(scppath,"/data/ifc_01_hydro/%s",filename); //Uh, yeah, probably not very secure... char *username = "******",*password = "******"; //Check out the file info struct stat fileinfo; stat(loclfile,&fileinfo); FILE* local = fopen(loclfile, "rb"); if(!local) { printf("Can't open local file %s\n", loclfile); return -1; } //Init ssh stuff long unsigned int hostaddr = inet_addr("128.255.26.166"); if(hostaddr < 0) { printf("Bad host address.\n"); return 1; } int rc = libssh2_init(0); if(rc) { printf("Problem initializing libssh2 (%i)\n",rc); return 1; } int sock = socket(AF_INET,SOCK_STREAM,0); if(-1 == sock) { printf("Failed to create socket\n"); return 1; } struct sockaddr_in sin; 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) { printf("Failed to connect!\n"); return 1; } //Create session instance and start it LIBSSH2_SESSION *session; session = libssh2_session_init(); if(!session) return 1; rc = libssh2_session_handshake(session, sock); if(rc) { printf("Failure establishing SSH session %i\n",rc); return 1; } //Authenticate const char* fingerprint = libssh2_hostkey_hash(session,LIBSSH2_HOSTKEY_HASH_SHA1); if(libssh2_userauth_password(session, username, password)) { printf("Authentication by password failed.\n"); error_code = 1; goto shutdown; } //Copy file LIBSSH2_CHANNEL *channel = libssh2_scp_send(session,scppath,fileinfo.st_mode & 0777,(unsigned long)fileinfo.st_size); if(!channel) { char *errmsg; int errlen; int err = libssh2_session_last_error(session, &errmsg, &errlen, 0); printf("Unable to open a session: (%d) %s\n", err, errmsg); error_code = 1; goto shutdown; } char mem[1024],*ptr; size_t nread; do { nread = fread(mem, 1, sizeof(mem), local); if (nread <= 0) { // end of file break; } ptr = mem; do { // write the same data over and over, until error or completion rc = libssh2_channel_write(channel, ptr, nread); if (rc < 0) { printf("ERROR %d\n", rc); break; } else { // rc indicates how many bytes were written this time ptr += rc; nread -= rc; } } while(nread); } while(1); //Tell server we are done libssh2_channel_send_eof(channel); libssh2_channel_wait_eof(channel); libssh2_channel_wait_closed(channel); //Clean up libssh2_channel_free(channel); channel = NULL; shutdown: if(session) { libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); } close(sock); if(local) fclose(local); if(!error_code && remove(loclfile)) printf("[%i]: Error deleting file %s.\n",my_rank,loclfile); libssh2_exit(); if(!error_code) printf("File %s uploaded!\n",loclfile); #endif return error_code; }
void CEasyssh::ConnectAP(const std::string str_usr, std::string str_passwd) { WSADATA wsadata; WSAStartup(MAKEWORD(2,0), &wsadata); int rc = libssh2_init(0); if (rc != 0) { TRACE(_T("libssh2_init Error\n")); m_bIsErr = true; return; } unsigned long hostaddr = inet_addr(m_strIP.c_str()); m_sock = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = htons(22); sin.sin_addr.s_addr = hostaddr; if (connect(m_sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) { TRACE(_T("connect socket Error\n")); m_bIsErr = true; return; } /* Create a session instance */ m_ssh_session = libssh2_session_init(); if (!m_ssh_session) { TRACE(_T("libssh2_session_init Error\n")); m_bIsErr = true; return; } /* tell libssh2 we want it all done non-blocking */ libssh2_session_set_blocking(m_ssh_session, 0); /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ while ((rc = libssh2_session_handshake(m_ssh_session, m_sock)) == LIBSSH2_ERROR_EAGAIN); if (rc) { TRACE(_T("libssh2_session_handshake Error\n")); m_bIsErr = true; return; } LIBSSH2_KNOWNHOSTS *nh = libssh2_knownhost_init(m_ssh_session); if(!nh) { /* eeek, do cleanup here */ TRACE(_T("libssh2_knownhost_init Error\n")); m_bIsErr = true; return; } /* 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); libssh2_knownhost_free(nh); while ((rc = libssh2_userauth_password(m_ssh_session, str_usr.c_str(), str_passwd.c_str())) == LIBSSH2_ERROR_EAGAIN); if (rc) { TRACE(_T("libssh2_userauth_password Error\n")); m_bIsErr = true; libssh2_session_disconnect(m_ssh_session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(m_ssh_session); closesocket(m_sock); libssh2_exit(); } m_bIsErr = false; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int sock = -1, i, rc; struct sockaddr_in sin; const char *fingerprint; char *userauthlist; LIBSSH2_SESSION *session = NULL; LIBSSH2_CHANNEL *channel; LIBSSH2_AGENT *agent = NULL; struct libssh2_agent_publickey *identity, *prev_identity = NULL; #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]; } 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); if (sock == -1) { fprintf(stderr, "failed to create socket!\n"); rc = 1; goto shutdown; } 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"); goto shutdown; } /* Create a session instance and start it up. This will trade welcome * banners, exchange keys, and setup crypto, compression, and MAC layers */ session = libssh2_session_init(); if (libssh2_session_handshake(session, sock)) { fprintf(stderr, "Failure establishing SSH session\n"); return 1; } /* At this point we havn't 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"); /* check what authentication methods are available */ userauthlist = libssh2_userauth_list(session, username, strlen(username)); printf("Authentication methods: %s\n", userauthlist); if (strstr(userauthlist, "publickey") == NULL) { fprintf(stderr, "\"publickey\" authentication is not supported\n"); goto shutdown; } /* Connect to the ssh-agent */ agent = libssh2_agent_init(session); if (!agent) { fprintf(stderr, "Failure initializing ssh-agent support\n"); rc = 1; goto shutdown; } if (libssh2_agent_connect(agent)) { fprintf(stderr, "Failure connecting to ssh-agent\n"); rc = 1; goto shutdown; } if (libssh2_agent_list_identities(agent)) { fprintf(stderr, "Failure requesting identities to ssh-agent\n"); rc = 1; goto shutdown; } while (1) { rc = libssh2_agent_get_identity(agent, &identity, prev_identity); if (rc == 1) break; if (rc < 0) { fprintf(stderr, "Failure obtaining identity from ssh-agent support\n"); rc = 1; goto shutdown; } if (libssh2_agent_userauth(agent, username, identity)) { printf("\tAuthentication with username %s and " "public key %s failed!\n", username, identity->comment); } else { printf("\tAuthentication with username %s and " "public key %s succeeded!\n", username, identity->comment); break; } prev_identity = identity; } if (rc) { fprintf(stderr, "Couldn't continue authentication\n"); goto shutdown; } /* We're authenticated now. */ /* Request a shell */ if (!(channel = libssh2_channel_open_session(session))) { fprintf(stderr, "Unable to open a session\n"); goto shutdown; } /* Some environment variables may be set, * It's up to the server which ones it'll allow though */ libssh2_channel_setenv(channel, "FOO", "bar"); /* 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"); goto skip_shell; } /* Open a SHELL on that pty */ if (libssh2_channel_shell(channel)) { fprintf(stderr, "Unable to request shell on allocated pty\n"); goto shutdown; } /* At this point the shell can be interacted with using * libssh2_channel_read() * libssh2_channel_read_stderr() * libssh2_channel_write() * libssh2_channel_write_stderr() * * Blocking mode may be (en|dis)abled with: libssh2_channel_set_blocking() * If the server send EOF, libssh2_channel_eof() will return non-0 * To send EOF to the server use: libssh2_channel_send_eof() * A channel can be closed with: libssh2_channel_close() * A channel can be freed with: libssh2_channel_free() */ skip_shell: if (channel) { libssh2_channel_free(channel); channel = NULL; } /* Other channel types are supported via: * libssh2_scp_send() * libssh2_scp_recv() * libssh2_channel_direct_tcpip() */ shutdown: libssh2_agent_disconnect(agent); libssh2_agent_free(agent); if(session) { libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); } if (sock != -1) { #ifdef WIN32 closesocket(sock); #else close(sock); #endif } printf("all done!\n"); libssh2_exit(); return rc; }
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; #if defined(HAVE_IOCTLSOCKET) long flag = 1; #endif char mem[1024*100]; size_t nread; char *ptr; struct stat fileinfo; 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) { 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_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; } } /* 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; do { /* write the same data over and over, until error or completion */ rc = libssh2_channel_write(channel, ptr, nread); if (LIBSSH2_ERROR_EAGAIN == rc) { /* must loop around */ continue; } else if (rc < 0) { fprintf(stderr, "ERROR %d\n", rc); break; } else { /* 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; }
SFtpConnectionCache::~SFtpConnectionCache() { closeAll(); libssh2_exit(); }
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; }
static void shutdown_ssh(void) { libssh2_exit(); }
int ssh2_auth(const char *hostip, const char *username, const char *password, char **errmsg) { unsigned long hostaddr; int sock; struct sockaddr_in sin; LIBSSH2_SESSION *session; int rc; LIBSSH2_KNOWNHOSTS *nh; struct StringBuffer *sberrmsg = new_string_buffer(); #ifdef WIN32 WSADATA wsadata; WSAStartup(MAKEWORD(2,0), &wsadata); #endif rc = libssh2_init (0); if (rc != 0) { sbprintf (sberrmsg, "libssh2 initialization failed (%d)\n", rc); *errmsg = free_string_buffer(sberrmsg, 0); return 1; } hostaddr = inet_addr(hostip); /* 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) { sbprintf(sberrmsg, "failed to connect!\n"); *errmsg = free_string_buffer(sberrmsg, 0); 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) { sbprintf(sberrmsg, "Failure establishing SSH session: %d\n", rc); *errmsg = free_string_buffer(sberrmsg, 0); return -1; } nh = libssh2_knownhost_init(session); if(!nh) { /* eeek, do cleanup here */ return 2; } /* We could authenticate via password */ while ((rc = libssh2_userauth_password(session, username, password)) == LIBSSH2_ERROR_EAGAIN); if (rc) { sbprintf(sberrmsg, "Authentication by password failed.\n"); *errmsg = free_string_buffer(sberrmsg, 0); } else { free_string_buffer(sberrmsg, 1); } libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif libssh2_exit(); return rc; }
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.c"; const char *sftppath="/tmp/TEST"; int rc; FILE *local; LIBSSH2_SFTP *sftp_session; LIBSSH2_SFTP_HANDLE *sftp_handle; LIBSSH2_SFTP_ATTRIBUTES attrs; char mem[1024*100]; size_t nread; char *ptr; #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 blocking */ libssh2_session_set_blocking(session, 1); /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_startup(session, sock); 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 */ if (libssh2_userauth_password(session, username, password)) { printf("Authentication by password failed.\n"); goto shutdown; } } else { /* Or by public key */ if (libssh2_userauth_publickey_fromfile(session, username, "/home/username/.ssh/id_rsa.pub", "/home/username/.ssh/id_rsa", password)) { printf("\tAuthentication by public key failed\n"); goto shutdown; } } fprintf(stderr, "libssh2_sftp_init()!\n"); sftp_session = libssh2_sftp_init(session); if (!sftp_session) { fprintf(stderr, "Unable to init SFTP session\n"); goto shutdown; } fprintf(stderr, "libssh2_sftp_open() for READ and WRITE!\n"); /* Request a file via SFTP */ sftp_handle = libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_WRITE|LIBSSH2_FXF_READ, LIBSSH2_SFTP_S_IRUSR|LIBSSH2_SFTP_S_IWUSR| LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IROTH); if (!sftp_handle) { fprintf(stderr, "Unable to open file with SFTP\n"); goto shutdown; } if(libssh2_sftp_fstat_ex(sftp_handle, &attrs, 0) < 0) { printf("libssh2_sftp_fstat_ex failed\n"); goto shutdown; } else libssh2_sftp_seek64(sftp_handle, attrs.filesize); printf("Did a seek to position %ld\n", (long) attrs.filesize); fprintf(stderr, "libssh2_sftp_open() a handle for APPEND\n"); if (!sftp_handle) { fprintf(stderr, "Unable to open file with SFTP\n"); goto shutdown; } fprintf(stderr, "libssh2_sftp_open() is done, now send data!\n"); do { nread = fread(mem, 1, sizeof(mem), local); if (nread <= 0) { /* end of file */ break; } ptr = mem; do { /* write data in a loop until we block */ rc = libssh2_sftp_write(sftp_handle, ptr, nread); if(rc < 0) break; ptr += rc; nread -= rc; } while (nread); } while (rc > 0); libssh2_sftp_close(sftp_handle); libssh2_sftp_shutdown(sftp_session); shutdown: libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif if (local) fclose(local); printf("all done\n"); libssh2_exit(); return 0; }
int main(int argc, char *argv[]) { unsigned long hostaddr = inet_addr("128.83.120.177"); int sock, rc; struct sockaddr_in sin; LIBSSH2_SFTP_HANDLE *sftp_handle; rc = libssh2_init (0); if (rc != 0) { fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); return 1; } 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; } session = libssh2_session_init(); if (!session) return -1; /* Tell libssh2 we are blocking */ libssh2_session_set_blocking(session, 1); /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_handshake(session, sock); 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 */ libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); if (libssh2_userauth_publickey_fromfile(session, username, "/home/ethan/.ssh/id_rsa.pub", "/home/ethan/.ssh/id_rsa", password)) { fprintf(stderr, "\tAuthentication by public key failed\n"); goto shutdown; } else { fprintf(stderr, "\tAuthentication by public key succeeded.\n"); } fprintf(stderr, "calling libssh2_sftp_init()...\n"); sftp_session = libssh2_sftp_init(session); if (!sftp_session) { fprintf(stderr, "Unable to init SFTP session\n"); goto shutdown; } fprintf(stderr, "calling libssh2_sftp_open()...\n"); /* Request a file via SFTP */ sftp_handle = libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_READ, 0); get_file_stat_struct(); if (!sftp_handle) { fprintf(stderr, "Unable to open file with SFTP: %ld\n", libssh2_sftp_last_error(sftp_session)); goto shutdown; } fprintf(stderr, "libssh2_sftp_open() is done, now receiving data...\n"); do { char mem[1024]; fprintf(stderr, "calling libssh2_sftp_read()...\n"); rc = libssh2_sftp_read(sftp_handle, mem, sizeof(mem)); if (rc > 0) { write(1, mem, rc); } else { break; } } while (1); // continue until it fails libssh2_sftp_close(sftp_handle); libssh2_sftp_shutdown(sftp_session); shutdown: libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); close(sock); fprintf(stderr, "all done\n"); libssh2_exit(); return 0; }
/* IPv6 ref: http://www.akkadia.org/drepper/userapi-ipv6.html */ int main(int argc, char** argv) { int rc, sock = -1; struct addrinfo *ai, *r; struct addrinfo hints; char bufhost[MAXHOSTBUFSIZE]; char bufport[MAXHOSTBUFSIZE]; LIBSSH2_SESSION *session; curstatebuf = malloc(MAXSTRSIZE); *curstatebuf = '\0'; /* Option defaults */ opt_host = "127.0.0.1"; opt_port = "ssh"; opt_username = "******"; if((rc = parse_options(argc, argv)) != 0) { curstate = CRITICAL; sprintf(curstatebuf, "Option parsing failed (%d). See stderr.", rc); nagios_exit(); } signal(SIGALRM, timeout_handler); alarm(opt_timeout); memset(&hints, '\0', sizeof(hints)); hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_ADDRCONFIG; dp("Connecting to %s:%s\n", opt_host, opt_port); int e = getaddrinfo(opt_host, opt_port, &hints, &ai); if (e != 0) { curstate = CRITICAL; sprintf(curstatebuf, "getaddrinfo: %s", gai_strerror(e)); nagios_exit(); } dp("Attempting connection to %s:%s\n", opt_host, opt_port); for(r = ai; r != NULL; r = r->ai_next) { dp("-> Trying family/socktype/proto %d/%d/%d\n", r->ai_family, r->ai_socktype, r->ai_protocol); sock = socket(r->ai_family, r->ai_socktype, r->ai_protocol); if (sock != -1 && connect(sock, r->ai_addr, r->ai_addrlen) == 0) break; if (sock != -1) { close(sock); sock = -1; } } if (sock == -1) { freeaddrinfo(ai); curstate = CRITICAL; sprintf(curstatebuf, "No socket"); nagios_exit(); } (void) getnameinfo(r->ai_addr, r->ai_addrlen, bufhost, sizeof (bufhost), bufport, sizeof(bufport), NI_NUMERICHOST|NI_NUMERICSERV); dp("Successfully connected to %s:%s\n", bufhost, bufport); freeaddrinfo(ai); /* libssh2_init and libssh2_exit was introduced in libssh2 1.2.5 */ #if LIBSSH2_VERSION_NUM >= 0x010205 if((rc = libssh2_init(0)) != 0) { curstate = CRITICAL; sprintf(curstatebuf, "libssh2 initialization failed (%d)", rc); nagios_exit(); } #endif session = libssh2_session_init(); if(libssh2_session_startup(session, sock) != 0) { char *err_msg; libssh2_session_last_error(session, &err_msg, NULL, 0); curstate = CRITICAL; sprintf(curstatebuf, "SSH error: %s", err_msg); nagios_exit(); } serverualist = strdup(libssh2_userauth_list(session, opt_username, strlen(opt_username))); dp("Server auth list: %s\n", serverualist); /* Run checks that were requested on the command line */ if(opt_uablacklist != NULL && strlen(opt_uablacklist)) uablacklistout = cslist_intersect(opt_uablacklist, serverualist); if(opt_uawhitelist != NULL && strlen(opt_uawhitelist)) uawhitelistout = cslist_difference(opt_uawhitelist, serverualist); dp("Matching blacklist: %s\n", uablacklistout); dp("Matching whitelist: %s\n", uawhitelistout); /* Construct status string */ curstatebufptr = curstatebuf; if(uablacklistout != NULL && strlen(uablacklistout)) { curstate = CRITICAL; sprintf(curstatebufptr, "Blacklisted SSH auth methods found (%s)", uablacklistout); curstatebufptr = strchr(curstatebuf, '\0'); } if(uawhitelistout != NULL && strlen(uawhitelistout)) { if(curstatebufptr > curstatebuf) { sprintf(curstatebufptr, ", "); curstatebufptr = strchr(curstatebuf, '\0'); } curstate = CRITICAL; sprintf(curstatebufptr, "Required SSH auth methods not found (%s)", uawhitelistout); curstatebufptr = strchr(curstatebuf, '\0'); } if(uablacklistout != NULL) free(uablacklistout); if(uawhitelistout != NULL) free(uawhitelistout); free(serverualist); libssh2_session_disconnect(session, "ok"); libssh2_session_free(session); close(sock); #if LIBSSH2_VERSION_NUM >= 0x010205 libssh2_exit(); #endif alarm(0); if(curstate == INIT) { curstate = OK; sprintf(curstatebuf, "SSH server parameters match expectations"); } nagios_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 *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) { fprintf(stderr, "Can't open 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); 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; } } 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); fprintf(stderr, "%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 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 = NULL; LIBSSH2_CHANNEL *channel; const char *username="******"; const char *password="******"; const char *loclfile="athan1.mp3"; const char *scppath="/home/jabouzic/test.c"; FILE *local; int rc; char mem[8001024]; size_t nread; char *ptr; struct stat fileinfo; #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 open 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); if(-1 == sock) { fprintf(stderr, "failed to create socket!\n"); return -1; } 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; /* ... start it up. This will trade welcome banners, exchange keys, * and setup crypto, compression, and MAC layers */ rc = libssh2_session_handshake(session, sock); 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 */ if (libssh2_userauth_password(session, username, password)) { fprintf(stderr, "Authentication by password failed.\n"); goto shutdown; } } else { /* Or by public key */ if (libssh2_userauth_publickey_fromfile(session, username, "/home/username/.ssh/id_rsa.pub", "/home/username/.ssh/id_rsa", password)) { fprintf(stderr, "\tAuthentication by public key failed\n"); goto shutdown; } } /* Send a file via scp. The mode parameter must only have permissions! */ channel = libssh2_scp_send(session, scppath, fileinfo.st_mode & 0777, (unsigned long)fileinfo.st_size); int file_size = (unsigned long)fileinfo.st_size; /*int file_parts = file_size / 1024 + 1; float percent = file_parts / 100;*/ int progress = 0; printf("size : %lu \n ", (unsigned long)fileinfo.st_size); if (!channel) { char *errmsg; int errlen; int err = libssh2_session_last_error(session, &errmsg, &errlen, 0); fprintf(stderr, "Unable to open a session: (%d) %s\n", err, errmsg); goto shutdown; } fprintf(stderr, "SCP session waiting to send file\n"); do { nread = fread(mem, 1, sizeof(mem), local); printf("nread : %d \n", (int)nread); if (nread <= 0) { /* end of file */ break; } ptr = mem; do { /* write the same data over and over, until error or completion */ rc = libssh2_channel_write(channel, ptr, nread); printf("rc : %d \n", rc); if (rc < 0) { fprintf(stderr, "ERROR %d\n", rc); break; } else { /* rc indicates how many bytes were written this time */ ptr += rc; nread -= rc; } progress += rc; printf("%f,0 pct \n ", ((float)progress / (float)file_size) * 100); } while (nread); } while (1); fprintf(stderr, "Sending EOF\n"); libssh2_channel_send_eof(channel); fprintf(stderr, "Waiting for EOF\n"); libssh2_channel_wait_eof(channel); fprintf(stderr, "Waiting for channel to close\n"); libssh2_channel_wait_closed(channel); libssh2_channel_free(channel); channel = NULL; shutdown: if(session) { libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); } #ifdef WIN32 closesocket(sock); #else close(sock); #endif if (local) fclose(local); fprintf(stderr, "all done\n"); libssh2_exit(); return 0; }
int main(int argc, char *argv[]) { unsigned long hostaddr; int rc, sock, i, auth_pw = 0; struct sockaddr_in sin; const char *fingerprint; char *userauthlist; LIBSSH2_SESSION *session; LIBSSH2_CHANNEL *channel; #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]; } 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 and start it up. This will trade welcome * banners, exchange keys, and setup crypto, compression, and MAC layers */ session = libssh2_session_init(); if (libssh2_session_startup(session, sock)) { fprintf(stderr, "Failure establishing SSH session\n"); return -1; } /* At this point we havn't 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"); /* check what authentication methods are available */ userauthlist = libssh2_userauth_list(session, username, strlen(username)); printf("Authentication methods: %s\n", userauthlist); if (strstr(userauthlist, "password") != NULL) { auth_pw |= 1; } if (strstr(userauthlist, "keyboard-interactive") != NULL) { auth_pw |= 2; } if (strstr(userauthlist, "publickey") != NULL) { auth_pw |= 4; } /* if we got an 4. argument we set this option if supported */ if(argc > 4) { if ((auth_pw & 1) && !strcasecmp(argv[4], "-p")) { auth_pw = 1; } if ((auth_pw & 2) && !strcasecmp(argv[4], "-i")) { auth_pw = 2; } if ((auth_pw & 4) && !strcasecmp(argv[4], "-k")) { auth_pw = 4; } } if (auth_pw & 1) { /* We could authenticate via password */ if (libssh2_userauth_password(session, username, password)) { printf("\tAuthentication by password failed!\n"); goto shutdown; } else { printf("\tAuthentication by password succeeded.\n"); } } else if (auth_pw & 2) { /* Or via keyboard-interactive */ if (libssh2_userauth_keyboard_interactive(session, username, &kbd_callback) ) { printf("\tAuthentication by keyboard-interactive failed!\n"); goto shutdown; } else { printf("\tAuthentication by keyboard-interactive succeeded.\n"); } } else if (auth_pw & 4) { /* Or by public key */ if (libssh2_userauth_publickey_fromfile(session, username, keyfile1, keyfile2, password)) { printf("\tAuthentication by public key failed!\n"); goto shutdown; } else { printf("\tAuthentication by public key succeeded.\n"); } } else { printf("No supported authentication methods found!\n"); goto shutdown; } /* Request a shell */ if (!(channel = libssh2_channel_open_session(session))) { fprintf(stderr, "Unable to open a session\n"); goto shutdown; } /* Some environment variables may be set, * It's up to the server which ones it'll allow though */ libssh2_channel_setenv(channel, "FOO", "bar"); /* 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"); goto skip_shell; } /* Open a SHELL on that pty */ if (libssh2_channel_shell(channel)) { fprintf(stderr, "Unable to request shell on allocated pty\n"); goto shutdown; } /* At this point the shell can be interacted with using * libssh2_channel_read() * libssh2_channel_read_stderr() * libssh2_channel_write() * libssh2_channel_write_stderr() * * Blocking mode may be (en|dis)abled with: libssh2_channel_set_blocking() * If the server send EOF, libssh2_channel_eof() will return non-0 * To send EOF to the server use: libssh2_channel_send_eof() * A channel can be closed with: libssh2_channel_close() * A channel can be freed with: libssh2_channel_free() */ skip_shell: if (channel) { libssh2_channel_free(channel); channel = NULL; } /* Other channel types are supported via: * libssh2_scp_send() * libssh2_scp_recv() * libssh2_channel_direct_tcpip() */ shutdown: libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing"); libssh2_session_free(session); #ifdef WIN32 closesocket(sock); #else close(sock); #endif printf("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; }