Getting Started with SSHPlex

Requirements: IPWorks SSH

The SSHPlex component allows performing SFTP, SCP, SExec, and SShell operations over a single SSH connection. Operations are performed asynchronously, so multiple operations can be performed in parallel.

Contents

Introduction to SSHPlex

SSHPlex is a component of IPWorks SSH, a suite of components aimed at providing robust solutions for building SSH secured applications. This article focuses specifically on the SSHPlex component.

The SSHPlex component combines the functionality of the SFTP, SCP, SExec, and SShell components. The asynchronous design of the component allows multiple operations to be performed simultaneously. For example, several SFTP file transfers may be started, and while the files are still transferring, commands may be executed over SExec. This is accomplished through the use of Operation Ids to track ongoing and completed operations, and the ChannelType property, which allows switching between SFTP, SCP, SExec, and SShell usage.

After establishing a connection, set ChannelType to the desired protocol and set any relevant properties for the operation. Calling the desired method will return an Operation Id (string) which identifies the operation in progress. A corresponding SSHPlexOperation object will also be added to the Operations collection to keep track of the operation in progress.

When the operation completes, a corresponding event will fire, indicating the success or failure of the operation. Examine the event parameters for further details. For instance, after calling the Upload method, the UploadComplete event will fire.

Ongoing operations may be cancelled at any time by passing the Operation Id to the CancelOperation method.

Note: The DoEvents method must be called frequently in order to process outstanding events. This is particularly important for SCP and SFTP operations. Call DoEvents in a loop for the best results.

Authentication

The first step to use the SSHPlex component is authenticating with the SSH host. Set the SSHUser and SSHPassword properties to authenticate via password authentication, or set the SSHCert property to authenticate via a certificate. Next, call SSHLogon and pass the SSH host address and port as parameters. During the connection, the SSHServerAuthentication event will fire, and the server's host key can be accepted from within the event by setting the Accept parameter to True. Additional authentication methods are detailed in the product documentation under the SSHAuthMode property.

SSHPlexControl.SSHUser = "username"; SSHPlexControl.SSHPassword = "password"; // attach event handler for SSHServerAuthentication SSHPlexControl.OnSSHServerAuthentication += (obj, ev) => { ev.Accept = true; }; SSHPlexControl.SSHLogon("sshHost", sshPort);

Channel Types

The ChannelType property determines the protocol used by the component and therefore the applicable methods and properties for each channel. Calling a non-applicable method for the current channel (such as calling the ListDirectory method while the ChannelType property is set to cstScp) will throw an Exception. Be sure to set the ChannelType to the correct channel before trying to use an applicable method/property. Possible channel types are:

  • SFTP
  • SCP
  • SExec
  • SShell

SFTP

When the ChannelType is set to cstSftp, the component implements the SSH File Transfer Protocol to transfer files through a secure channel between a local host and a remote host and offers multiple methods for browsing filesystems and manipulating files and directories.

Applicable Methods Applicable Properties
  • Append
  • CreateFile
  • DeleteFile
  • Download
  • ListDirectory
  • MakeDirectory
  • RemoveDirectory
  • UpdateFileAttributes
  • SetDownloadStream
  • SetUploadStream
  • Upload
  • DirList
  • FileAttributes
  • FileExists
  • LocalFile
  • Overwrite
  • RemoteFile
  • RemotePath
  • StartByte

SCP

When the ChannelType is set to cstScp, the component implements the Secure Copy Protocol to transfer files through a secure channel between a local host and a remote host and offers a download and an upload method to transfer files.

Applicable Methods Applicable Properties
  • Download
  • SetDownloadStream
  • SetUploadStream
  • Upload
  • FilePermissions
  • LocalFile
  • Overwrite
  • RemoteFile
  • RemotePath

SExec

When the ChannelType is set to cstSExec, the component is able to execute commands on a remote SSH server. Each time a command is sent to the remote host, a new session is started, the component processes any output from the remote host, and the session is closed. This channel is useful for single commands to be executed on the remote host.

Applicable Methods Applicable Properties
  • Execute
  • Command
  • Stdin

SShell

When the ChannelType is set to cstSShell, the component is able to execute commands on a remote SSH server. The component will open the user's default shell and maintain a connection while processing any output from the remote shell. This channel is useful for maintaining a connection to the remote shell to execute multiple commands.

Applicable Methods Applicable Properties
  • Execute
  • Command
  • Stdin

Listing Directories (SFTP)

The ListDirectory method queries the remote host for files and folders specified by the RemotePath property. If the RemoteFile property is set, the component will use the value as a filemask and return all files matching the filemask. When this method is called, an Operation Id which identifies the operation in progress is returned. This operation can be cancelled by passing the Operation Id to the CancelOperation method. The results are provided through the DirList event along with the DirList property.

Note: this functionality is only applicable while the ChannelType is set to cstSftp. See Channel Types for a list of applicable methods for each ChannelType.

Example

SSHPlexControl.RemoteFile = ""; //Clear filemask SSHPlexControl.RemotePath = "MyFolder"; string opId = SSHPlexControl.ListDirectory(); // ListDirectory operates async so we must wait for it to finish while (SSHPlexControl.Operations.Keys.Contains(opId)) { SSHPlexControl.DoEvents(); } for (int i = 0; i < SSHPlexControl.DirList.Count; i++) { Console.WriteLine(SSHPlexControl.DirList[i].FileName); Console.WriteLine(SSHPlexControl.DirList[i].FileSize); Console.WriteLine(SSHPlexControl.DirList[i].FileTime); Console.WriteLine(SSHPlexControl.DirList[i].IsDir); } Using the RemoteFile property as a filemask: SSHPlexControl.RemoteFile = "*.txt"; SSHPlexControl.ListDirectory(); // ListDirectory will query the remote host for all .txt files

Downloading Files (SFTP and SCP)

Downloading files from a remote host is easy to do with the SSHPlex component. First, setRemoteFile to the name the file to download. If RemoteFile only specifies a filename it will be downloaded from the path specified by RemotePath. RemoteFile may also be set to an absolute path.

Note: this functionality is only applicable while the ChannelType is set to cstSftp or cstScp. See Channel Types for a list of applicable methods for each ChannelType.

Example

SSHPlexControl.Localfile = "C:\localfile.txt"; SSHPlexControl.RemoteFile = "remotefile.txt"; string operationID = SSHPlexControl.Download(); // Use Path in RemoteFile SSHPlexControl.Localfile = "C:\localfile2.txt"; SSHPlexControl.RemoteFile = "folder/remotefile2.txt"; string operationID = SSHPlexControl.Download();

Resuming Downloads (SFTP)

The component also supports resuming failed downloads by using the StartByte property. If a download is interrupted or cancelled, set StartByte to the appropriate offset before calling this method to resume the download.

Note: this functionality is only applicable while the ChannelType is set to cstSftp. See Channel Types for a list of applicable methods for each ChannelType.

string localFile = "C:\localfile.txt"; SSHPlexControl.Localfile = localFile; SSHPlexControl.RemoteFile = "remotefile.txt"; string operationID = SSHPlexControl.Download(); // Cancel Download using the CancelOperation method SSHPlexControl.CancelOperation(operationID); // Get the size of the partially downloaded temp file and set StartByte SSHPlexControl.StartByte = new FileInfo(localFile).Length; // Resume download string operationID = SSHPlexControl.Download();

Downloading with a Filemask (SCP)

The component also supports downloading multiple files from the remote host by using a filemask. If RemoteFile is set to a filemask, it will download all files matching the filemask to the local directory specified by the LocalFile property.

Note: this functionality is only applicable while the ChannelType is set to cstScp. See Channel Types for a list of applicable methods for each ChannelType.

SSHPlexControl.LocalFile = "localDirectory"; SSHPlexControl.RemotePath = "remoteDirectory"; SSHPlexControl.RemoteFile = "*.txt"; // Downloads all .txt files from the directory specified by RemotePath to the directory specified by LocalFile SSHPlexControl.Download();

Uploading Files (SFTP and SCP)

Uploading files to a remote host is easy to do with the SSHPlex component. First, set LocalFile to the name the file to upload. RemoteFile should then be set to either a relative or an absolute path. If RemoteFile is not an absolute path, it will be uploaded relative to RemotePath.

Note: this functionality is only applicable while the ChannelType is set to cstSftp or cstScp. See Channel Types for a list of applicable methods for each ChannelType.

Example

SSHPlexControl.Localfile = "C:\localfile.txt"; SSHPlexControl.RemoteFile = "remotefile.txt"; string operationID = SSHPlexControl.Upload(); // Use Path in RemoteFile SSHPlexControl.Localfile = "C:\localfile2.txt"; SSHPlexControl.RemoteFile = "folder/remotefile2.txt"; string operationID = SSHPlexControl.Upload();

Resuming Uploads (SFTP)

The component also supports resuming failed uploads by using the StartByte property. If a upload is interrupted or cancelled, set StartByte to the appropriate offset before calling this method to resume the upload.

Note: this functionality is only applicable while the ChannelType is set to cstSftp. See Channel Types for a list of applicable methods for each ChannelType.

string localFile = "C:\localfile.txt"; SSHPlexControl.Localfile = localFile; SSHPlexControl.RemoteFile = "remotefile.txt"; string operationID = SSHPlexControl.Upload(); // Cancel Upload using the CancelOperation method SSHPlexControl.CancelOperation(operationID); // Get the size of the partially uploaded temp file and set StartByte SSHPlexControl.StartByte = SSHPlexControl.FileAttributes.Size; // Resume upload string operationID = SSHPlexControl.Upload();

Cancelling Operations

Once an operation has been started by calling a method, it may later be cancelled by passing the Operation Id associated with the operation to be cancelled to the CancelOperation method.

// Start a large file upload string opId = SSHPlexControl.Upload(); // Begin other operations string opId2 = SSHPlexControl.ListDirectory(); // Cancel file upload sshplex.CancelOperation(opId);

Additional SFTP Functionality

When the ChannelType property is set to cstSftp, additional methods are available including:

  • Append
  • CreateFile
  • DeleteFile
  • MakeDirectory
  • RemoveDirectory
  • RenameFile
  • UpdateFileAttributes
Please see the product documentation for more details.

Remote Execution

The SExec and SShell channel types provide a way to execute commands on the SSH server. SExec is useful for executing single commands. SShell is useful when maintaining and interactive session.

Using SExec

When the ChannelType is set to cstSExec, commands may be executed on the remote hosts default shell. After a command is processed, the session is closed.

Note: the Execute method may be cancelled by the CancelOperation method, but using the Command or Stdin property will block operation while the component waits for the remote host to respond. Also, only the Execute method will fire the ExectuteComplete event.

// Event handler for stdout from remote host SSHPlexControl.OnStdout += (obj, ev) => { Console.WriteLine(ev.Text); }; SSHPlexControl.ChannelType = SSHPlexChannelTypes.cstSExec; SSHPlexControl.Command = "ls"; // Executes "ls" command on remote host's default shell SSHPlexControl.Stdin = "cd remoteDirectory\n"; // Executes "cd remoteDirectory" command on remote host's default shell SSHPlexControl.Execute("ls"); // Executes "ls" command on remote host's default shell - will be in default directory, not in "remoteDirectory"

Using SShell

When the ChannelType is set to cstSShell, commands may be executed on the remote hosts default shell. After a command is processed, the sesssion remains open so more commands may be executed in the current context of the remote host's shell.

Note: the Execute method may be cancelled by the CancelOperation method, but using the Command or Stdin property will block operation while the component waits for the remote host to respond. Also, only calling the Execute method will fire the ExecuteComplete event.

// Event handler for stdout from remote host SSHPlexControl.OnStdout += (obj, ev) => { Console.WriteLine(ev.Text); }; SSHPlexControl.ChannelType = SSHPlexChannelTypes.cstSShell; SSHPlexControl.Command = "ls"; // Executes "ls" command on remote host's default shell SSHPlexControl.Stdin = "cd remoteDirectory\n"; // Executes "cd remoteDirectory" command on remote host's default shell SSHPlexControl.Execute("ls"); // Executes "ls" command on remote host's default shell in remote host's default directory - will be in "remoteDirectory", not in default directory

We appreciate your feedback.  If you have any questions, comments, or suggestions about this article please contact our support team at kb@nsoftware.com.