SSH and SFTP communication in C++ using libssh2.
For some time I have been looking around for some nice C or C++ library to enable communication using the SSH and/or SFTP protocols. Finally, I found the eminent library called libssh2 on http://www.libssh2.org (or on Sourceforge). In order to incorporate this library in my project, I created a C++ class called PJSSH that encapsulates the SSH and SFTP communication details.
A relatively simple interface is provided for the user of the class, exposing some few methods:
- To execute a command on the remote server using SSH.
- To read a remote file through SFTP and write it on a std::ostream reference.
- To write the data provided by a std::istream reference onto a remote file through SFTP.
For your convenience, I provide a stripped down version of the class declaration (the header file) below. Update 2008-05-17: There is a complete source code and a test program available, see the menu.
#ifndef PJSSH_H #define PJSSH_H #include <libssh2.h> #include <iosfwd> /// Class that encapsulates SSH and/or SFTP communications. /// @author Peter Jansson http://peter.jansson.net/ /// @date 2008-05-10 class PJSSH { public: /// Create a SSH communications capable object. /// The SSH session will be initialized to communicate to the /// host:port specified in the arguments to this constructor, /// using the login credentials supplied. PJSSH(const char* aHostName,const int& aPortNumber,const char* aUserName,const char* aPassword); /// Destory this instance. /// The SSH session will be unitialized. ~PJSSH(); /// Execute the supplied command through the established SSH session. void ExecuteCommand(const char* aCommand) const; /// Get a file from the remote system and write as is (i.e. binary) /// on the supplied stream void GetFile(const char* aRemoteFileName,std::ostream& aStream) const; /// Read from the supplied stream and put it as is (i.e. binary) /// on the remote file. /// The remote file will be truncated and over written if it exists. void PutStream(std::istream& aStream,const char* aRemoteFileName) const; protected: /// We don't really support copying at this stage. PJSSH(const PJSSH &); /// We don't really support assignment copy at this stage. PJSSH & operator=(const PJSSH &); }; #endif // define PJSSH_H