Sample SFTP client code and sftp client code

Source: Internet
Author: User
Tags sftp link

Sample SFTP client code and sftp client code
SFTP client code example

Environment:Libssh2 1.4.3, zlib-1.2.8, openssl-1.0.1g

Author:Kagula

Last update date:

From Idea 2013, there are two projects in it. You only need to compile the libssh2 project. Before compilation, add the header files of zlib and openssl and the link location of the library file. If you are prompted to not find msvcrt. lib after compiling libssh2, add the following path for the link library.

C: \ Program Files (x86) \ Microsoft VisualStudio 12.0 \ VC \ lib

The following link path cannot be found: ws2_32.lib or odbc32.lib.

C: \ Program Files (x86) \ MicrosoftSDKs \ Windows \ v7.1A \ Lib

After compilation, the file is output to \ libssh2-1.4.3 \ win32 \ Release_lib path

The following is the sample code of the SFTP client.

# Include "SFTP_Libssh2.h" # include <iostream> int main (int argc, char * argv []) {// the following code executes kagula: network during process initialization:: SFTP_Init (); // test SFTP link kagula: network: SFTP_Libssh2 * client = kagula: network: SFTP_Libssh2: Inst (); std :: string ip = "192.168.19.130"; uint16_t port = 22; std: string usr = "kagula"; std: string pwd = "123456 "; if (false = client-> IsAbilityConn (ip, port, usr, pwd) {std: cout <client-> str LastError <std: endl; return-1 ;}// Test File Upload, d: \ temp \ a.html if (0! = Client-> upload (ip, 22, usr, pwd, "d :\\ temp \ a.html", "/home/kagula/a.html") {std :: cout <"Error:" <client-> strLastError <std: endl;} else {std: cout <client-> strLastError <std :: endl;} // download the test file if (0! = Client-> download (ip, 22, usr, pwd, "/home/kagula/a.html", "d: \ temp \ B .html") {std :: cout <"Error:" <client-> strLastError <std: endl;} else {std: cout <client-> strLastError <std :: endl;} // when the process preparation is complete and resources are released, run the following code kagula: network: SFTP_Exit (); return 0 ;}

SFTP_Libssh2.h

# Pragma once # include <string> # include <atomic>/* function: SFTP file transfer function last updated: Introduction: sftp is easily implemented using the Libssh2 library, ssh2 client, here shows how to implement Sftp client code test environment: Windows 8.1 64bit, Visual Studio 2013 Professional SP1 OpenSSL 1.0.1g, zlib-1.2.8, libssh2 1.4.3 Win32 console project note: the "libssh2.dll" file needs to be copied to the current project path for dynamic links. Note: the original code supports multithreading and is simplified when the application is extracted, you can modify the code so that it supports uploading or downloading multiple files at the same time. Suggestion: [1] a third-party library directly downloads the source code and compiles it by itself to avoid a lot of trouble in the library due to different compiler versions or different links set. [2] Reading the code and making corresponding modifications as required by the project. Additional reading materials: using the libssh2 library to implement ssh2 clients supporting Password parameters unzip kagula {namespace network {int SFTP_Init (); void SFTP_Exit (); class SFTP_BKCall {public:/* progress return value range [0.0, 1.0] */virtual void OnProgress (float progress) = 0 ;}; class SFTP_Libssh2 {public: static SFTP_Libssh2 * Inst () {static SFTP_Libssh2 inst; return & inst;}/* entry parameter instructions ip Address: Just fill in an ip address, for example, "1 27.0.0.1 ". Port: port. The default port of the SFTP server is 22. Username: password: sftppath: Start with remote path "/", for example, "/a.jpg" localpath: local path, for example, "d: \ temp \ test.jpg" strLastError: if the exit parameter of the error message is returned, it is not equal to zero, indicating that the error failed! */Int upload (std: string ip, unsigned short port, std: string username, std: string password, std: string localpath, std: string remotepath ); int download (std: string ip, unsigned short port, std: string username, std: string password, std: string sftppath, std: string localpath ); // test whether the SFTP server can connect to bool IsAbilityConn (std: string ip, unsigned short port, std: string username, std: string password ); // set the return function void SetBKCall (SFTP_BKCall * bkCall) {m_bkCall = bkCall;} // stores the latest error message std: string strLastError; // used to stop the current upload or download thread void stop () {m_isBreak.store (true);} private: SFTP_Libssh2 (): m_bkCall (NULL) {m_isBreak.store (false );}; // prevent direct initialization of SFTP_Libssh2 (const SFTP_Libssh2 &); // prevent copy and replication of SFTP_Libssh2 & operator = (const SFTP_Libssh2 &); // prevent allocation (call of operator functions) SFTP_BKCall * m_bkCall; std: atomic_bool m_isBreak; // bool value with read/write protection };}}


SFTP_Libssh2.cpp

// SFTP_Libssh2.cpp file list # include "outputs" # include <libssh2.h> # include <strong> # ifdef HAVE_WINSOCK2_H # include <winsock2.h> # endif # ifdef HAVE_SYS_SOCKET_H # include <sys/socket. h> # endif # ifdef HAVE_NETINET_IN_H # include <netinet/in. h> # endif # ifdef HAVE_UNISTD_H # include <unistd. h> # endif # ifdef HAVE_ARPA_INET_H # include <arpa/inet. h> # endif # ifdef HAVE_SYS_TIME_H # include <sys/time. h> # endif # include <Sys/types. h> # include <fcntl. h> # include <errno. h> # include <stdio. h> # include <ctype. h> # include <sstream> # include <iomanip> # pragma comment (lib, "ws2_32.lib") # pragma comment (lib, "libeay32.lib") # pragma comment (lib, "libssh2.lib") namespace kagula {namespace network {// called during process initialization // if it is not 0, initialization fails! Int SFTP_Init () {WSADATA wsadata; int rc = WSAStartup (MAKEWORD (2, 0), & wsadata); if (rc! = 0) {return rc;} rc = libssh2_init (0); return rc;} // call void SFTP_Exit () {libssh2_exit (); WSACleanup () when the process ends ();} bool SFTP_Libssh2: IsAbilityConn (std: string ip, unsigned short port, std: string username, std: string password) {unsigned long hostaddr; struct sockaddr_in sin; const char * fingerprint; LIBSSH2_SESSION * session; int rc; bool bR = false; FILE * local; LIBSSH2_SFTP * sftp_session; LIBSSH2_SFTP_HANDLE * sftp _ Handle; hostaddr = inet_addr (ip. c_str (); // hostaddr = htonl (0x7F000001); // create a connection int sock = socket (AF_INET, SOCK_STREAM, 0); sin. sin_family = AF_INET; sin. sin_port = htons (port); sin. sin_addr.s_addr = hostaddr; if (connect (sock, (struct sockaddr *) (& sin), sizeof (struct sockaddr_in ))! = 0) {std: ostringstream ostr; ostr <"[" <_ FILE _ <"] [" <_ LINE _ <"] failed to connect" <ip <"! "<Std: endl; strLastError = ostr. str (); return bR;} // create a dialog instance session = libssh2_session_init (); if (! Session) {closesocket (sock); return bR;} // set call blocking libssh2_session_set_blocking (session, 1); // perform handshake rc = libssh2_session_handshake (session, sock ); if (rc) {std: ostringstream ostr; ostr <"[" <_ FILE _ <"] [" <_ LINE _ <"] Failure establishing SSH session: "<rc <std: endl; strLastError = ostr. str (); libssh2_session_free (session); closesocket (sock); return bR;} // check the host fingerprint std: ostringstream ostr; fingerp Rint = libssh2_hostkey_hash (session, LIBSSH2_HOSTKEY_HASH_SHA1); ostr <"Fingerprint:"; for (int I = 0; I <20; I ++) {unsigned char c = fingerprint [I]; int nT = c; ostr <std: hex <std: setw (2) <std :: setfill ('0') <nT;} strLastError = ostr. str (); // verify the login user identity using the password if (libssh2_userauth_password (session, username. c_str (), password. c_str () {std: ostringstream ostr; ostr <"[" <_ FILE _ <"] [" <_ _ LINE _ <"] Authentication by password failed. "<std: endl; strLastError = ostr. str (); goto shutdown;} sftp_session = libssh2_sftp_init (session); if (! Sftp_session) {std: ostringstream ostr; ostr <"[" <_ FILE _ <"] [" <_ LINE _ <"] Unable to init SFTP session" <std:: endl; strLastError = ostr. str (); goto shutdown;} bR = true; disconnect (sftp_session); shutdown: libssh2_session_disconnect (session, "Normal Shutdown, Thank you for playing"); libssh2_session_free (session ); closesocket (sock); return bR;}/* source reference address http://www.libssh2.org/example S/sftp_write.html */int SFTP_Libssh2: upload (std: string ip, unsigned short port, std: string username, std: string password, std: string localpath, std: string remotepath) {if (ip. length () <1 | username. length () <1 | password. length () <1 | localpath. length () <1 | remotepath. length () <1) {return-1;} int nR = 0; unsigned long hostaddr; struct sockaddr_in sin; const char * fingerprint; LIBSSH2_SESSION * sessio N; int rc =-1; FILE * local = NULL; LIBSSH2_SFTP * sftp_session; LIBSSH2_SFTP_HANDLE * sftp_handle; hostaddr = inet_addr (ip. c_str (); // hostaddr = htonl (0x7F000001); if (fopen_s (& local, localpath. c_str (), "rb ")! = 0) {std: ostringstream ostr; ostr <"[" <_ FILE _ <"] [" <_ LINE _ <"] Can't open local file" <localpath <std:: endl; strLastError = ostr. str (); return-2;} // obtain the entire size of the file to be uploaded. fseek (local, 0, SEEK_END); size_t filesize = ftell (local); // local file size, which is referenced by fseek (local, 0, SEEK_SET) in readFromDisk ); // reset the file pointer to the file header // new connection int sock = socket (AF_INET, SOCK_STREAM, 0); sin. sin_family = AF_INET; sin. sin_port = hton S (port); sin. sin_addr.s_addr = hostaddr; if (connect (sock, (struct sockaddr *) (& sin), sizeof (struct sockaddr_in ))! = 0) {std: ostringstream ostr; ostr <"[" <_ FILE _ <"] [" <_ LINE _ <"] failed to connect" <ip <std:: endl; strLastError = ostr. str (); fclose (local); return-3;} // create a session instance session = libssh2_session_init (); if (! Session) {fclose (local); closesocket (sock); return-4;} // call libssh2libssh2_session_set_blocking (session, 1) in blocking mode; // perform handshake rc = libssh2_session_handshake (session, session, sock); if (rc) {std: ostringstream ostr; ostr <"[" <_ FILE _ <"] [" <_ LINE _ <"] Failure establishing SSH session: "<rc <std: endl; strLastError = ostr. str (); fclose (local); libssh2_session_free (session); closesocket (sock); return-5 ;}// Obtain the host fingerprint std: ostringstream ostr; Fingerprint = libssh2_hostkey_hash (session, LIBSSH2_HOSTKEY_HASH_SHA1); ostr <"fingerprint:"; for (int I = 0; I <20; I ++) {unsigned char c = fingerprint [I]; int nT = c; // This conversion is to prevent the symbol bit extension ostr <std: hex <std :: setw (2) <std: setfill ('0') <nT;} strLastError = ostr. str (); // verify if (libssh2_userauth_password (session, username. c_str (), password. c_str () {std: ostringst Ream ostr; ostr <"[" <_ FILE _ <"] [" <_ LINE _ <"] Authentication by password failed [" <username <<"] [" <password <"]" <rc <std:: endl; strLastError = ostr. str (); goto shutdown;} sftp_session = libssh2_sftp_init (session); if (! Sftp_session) {std: ostringstream ostr; ostr <"[" <_ FILE _ <"] [" <_ LINE _ <"] Unable to init SFTP session" <std:: endl; strLastError = ostr. str (); goto shutdown;} // send a new file request to the SFTP server sftp_handle = libssh2_sftp_open (sftp_session, remotepath. c_str (), LIBSSH2_FXF_WRITE | LIBSSH2_FXF_CREAT | LIBSSH2_FXF_TRUNC, required | LIBSSH2_SFTP_S_IWUSR | LIBSSH2_SFTP_S_IRGRP | required); If (! Sftp_handle) {std: ostringstream ostr; ostr <"[" <_ FILE _ <"] [" <_ LINE _ <"] Unable to open file with SFTP. ip = "<ip <"] remotepath = ["<remotepath <"] "<std: endl; strLastError = ostr. str (); nR =-1; goto shutdown;} char mem [1024*16]; size_t nread; char * ptr; size_t count = 0; do {nread = fread (mem, 1, sizeof (mem), local); if (nread <= 0) {// reach the break at the end of the file;} ptr = mem; do {// write data to the server until the data is written Bi rc = libssh2_sftp_write (sftp_handle, ptr, nread); if (rc <0) break; ptr + = rc; count + = nread; nread-= rc; // if a callback is set, perform the callback if (m_bkCall) {float p = count/(float) filesize; m_bkCall-> OnProgress (p);} // callback. end} while (nread); if (m_isBreak.load () = true) {std: ostringstream ostr; ostr <"[" <_ FILE _ <"] [" <_ LINE _ <"] the FILE upload task is break by the user! "<Std: endl; strLastError = ostr. str (); nR =-6; break;} while (rc> 0); libssh2_sftp_close (sftp_handle); merge (sftp_session); shutdown: libssh2_session_disconnect (session, "Normal Shutdown, thank you for playing "); libssh2_session_free (session); closesocket (sock); fclose (local); return nR; // return "0" to indicate success}/* Source code reference address: http://www.oschina.net/code/snippet_12_201717824/int SFTP_Libssh2: download (std: stri Ng ip, unsigned short port, std: string username, std: string password, std: string sftppath, std: string localpath) {unsigned long hostaddr; int sock, i, auth_pw = 0; struct sockaddr_in sin; const char * fingerprint; char * userauthlist; Comment * session; int rc; Comment * sftp_session; Comment * sftp_handle; hostaddr = inet_addr (ip. c_str (); // hostaddr = htonl (0x7F000001);/** The appli Cation 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 (port); sin. sin_addr.s_addr = hostaddr; if (connect (sock, (struct sockaddr *) (& sin), sizeof (struct sockaddr_in ))! = 0) {std: ostringstream ostr; ostr <"[" <_ FILE _ <"] [" <_ LINE _ <"] connection failed! "<Std: endl; strLastError = ostr. str (); 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_handshake (session, sock); if (rc) {std :: ostringstream ostr; ostr <"[" <_ FILE _ <"] [" <_ LINE _ <"] failed to establish an SSH session" <rc <std:: endl; s TrLastError = ostr. str (); 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); std: ostringstream ostr; fingerprint = libssh2_hostkey_hash (session, LIBSSH2_HOSTKEY_HASH_SHA1); ostr <"Fingerprint:"; for (int I = 0; I <20; I ++) {unsigned char c = fingerprint [I]; int nT = c; ostr <std: hex <std: setw (2) <std: setfill ('0') <nT ;} strLastError = ostr. str ();/* check what authentication methods are available */userauthlist = libssh2_userauth_list (session, username. c_str (), username. length (); if (strstr (userauthlist, "password") = NULL) {std:: Ostringstream ostr; ostr <"[" <_ FILE _ <"] [" <_ LINE _ <"] the server does not support password verification! "<Std: endl; strLastError = ostr. str (); goto shutdown;}/* We cocould authenticate via password */if (libssh2_userauth_password (session, username. c_str (), password. c_str () {std: ostringstream ostr; ostr <"[" <_ FILE _ <"] [" <_ LINE _ <"] incorrect password! "<Std: endl; strLastError = ostr. str (); goto shutdown;} sftp_session = libssh2_sftp_init (session); if (! Sftp_session) {std: ostringstream ostr; ostr <"[" <_ FILE _ <"] [" <_ LINE _ <"] failed to initialize the FTL conversation! "<Std: endl; strLastError = ostr. str (); goto shutdown;}/* Request a file via SFTP */sftp_handle = libssh2_sftp_open (sftp_session, sftppath. c_str (), LIBSSH2_FXF_READ, 0); if (! Sftp_handle) {std: ostringstream ostr; ostr <"[" <_ FILE _ <"] [" <_ LINE _ <"] failed to open the FILE! "<Libssh2_sftp_last_error (sftp_session) <std: endl; strLastError = ostr. str (); goto shutdown;} FILE * stream; if (fopen_s (& stream, localpath. c_str (), "wb") = 0) {do {char mem [1024];/* loop until we fail */rc = libssh2_sftp_read (sftp_handle, mem, sizeof (mem); if (rc> 0) {// from memory to disk fwrite (mem, 1, rc, stream);} else {break ;}} while (1); fclose (stream);} else {std: ostringstream ostr; ostr <"[" <_ FILE _ <"] [" <_ LINE _ <"] failed to create local FILE" <localpath <std:: endl; strLastError = ostr. str ();} libssh2_sftp_close (sftp_handle); terminate (sftp_session); shutdown: suspend (session, "Normal Shutdown, Thank you for playing"); libssh2_session_free (session ); closesocket (sock); // INVALID_SOCKETreturn 0 ;}}}



I want to upload files to sftp. How does the c # Code specify the sftp port?

New Tamir. SharpSsh. java. String
I only know this but cannot write it ..

What is the encryption algorithm used for SFTP?

SFTP (SSH or Secure FTP) is encrypted and verified based on SSH, while SSH is verified and encrypted through public key encryption algorithms. Specific SSH standards include:

* RFC 4250, The Secure Shell (SSH) Protocol Assigned Numbers
* RFC 4251, The Secure Shell (SSH) Protocol Architecture
* RFC 4252, The Secure Shell (SSH) Authentication Protocol
* RFC 4253, The Secure Shell (SSH) Transport Layer Protocol
* RFC 4254, The Secure Shell (SSH) Connection Protocol
* RFC 4255, Using DNS to Securely Publish Secure Shell (SSH) Key Fingerprints
* RFC 4256, Generic Message Exchange Authentication for the Secure Shell Protocol (SSH)
* RFC 4335, The Secure Shell (SSH) Session Channel Break Extension
* RFC 4344, The Secure Shell (SSH) Transport Layer Encryption Modes
* RFC 4345, Improved Arcfour Modes for the Secure Shell (SSH) Transport Layer Protocol

Specific SSH/SFTP code can be used to study open-source openSSH source code
Www.openssh.com/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.