SSHPlex Class

Properties   Methods   Events   Configuration Settings   Errors  

SSHPlex is a multiplexed class that operates over a single SSH connection and allows file transfers using SFTP or SCP. It can also remotely execute commands using SExec or SShell.

Syntax

ipworksssh.Sshplex

Remarks

The SSHPlex class combines the functionality of the SCP class, the SFTP class, the SExec class, and the SShell class. All operations are performed over a single SSH connection.

The asynchronous design of the class 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 complete operations, and ChannelType 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 will also be added to the Operations collection.

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 Upload the UploadComplete event will fire.

Ongoing operations may be canceled 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 best results.

Authentication

The SSHHost and SSHPort properties specify the SSH server to use. The SSHUser and SSHPassword properties allow the client to authenticate itself with the server. The SSHServerAuthentication event and/or SSHAcceptServerHostKey property allow you to check the server identity. Finally, the SSHStatus event provides information about the SSH handshake.

Example (Logging On)


SSHPlexControl.SSHUser = "username"
SSHPlexControl.SSHPassword = "password"
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. Valid values are:

ChannelTypeDescriptionApplicable MethodsApplicable Properties
0 (cstSShell - default) An interactive shell for command execution
1 (cstSExec) Command execution using SExec
2 (cstScp) SCP File Transfer
3 (cstSftp) SFTP File Transfer

Note that CancelOperation and other methods not explicitly listed above are applicable to all channel types.

Listing Files and Folders

ListDirectory lists files and folders from the path specified by RemotePath.

The directory entries are provided through the DirList event and also via the DirList property.

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);
}

The RemoteFile property may also be used as a filemask when listing files. For instance:

SSHPlexControl.RemoteFile = "*.txt";
SSHPlexControl.ListDirectory();

Note: Since RemoteFile is used as a filemask be sure to clear or reset this value before calling ListDirectory

Downloading Files

The Download method downloads a specific file.

Set RemoteFile to the name of the file to download before calling this method. 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.

The file will be downloaded to the stream specified (if any) by SetDownloadStream. If a stream is not specified and LocalFile is set the file will be saved to the specified location.

Code 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

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


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();

Uploading Files

The Upload method is used to upload files. Set LocalFile to the name of the file to upload before calling this method. If SetUploadStream is used to set an upload stream the data to upload is taken from the stream instead.

RemoteFile should be set to either a relative or absolute path. If RemoteFile is not an absolute path it will be uploaded relative to RemotePath.

Code 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

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


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();

Remote Execution

Executing commands on a remote host is done by using the cstSExec or cstSShell ChannelType.

To execute a command, simply call the Execute method or set the Command property with the command you wish to execute. Further input may be supplied via the Stdin property.

The output of the command is returned through the Stdout event. Errors during command execution (the stderr stream) are given by the Stderr event.

Property List


The following is the full list of the properties of the class with short descriptions. Click on the links for further details.

ChannelTypeSpecifies the Channel Type to be used by the class.
CommandThe command to be sent to the remote host.
ConnectedTriggers a connection or disconnection.
DirListCollection of entries resulting in the last directory listing.
FileAttributesThe attributes of the RemoteFile .
FileExistsReturns true if the file specified by RemoteFile exists on the remote server.
FilePermissionsThe file permissions for the RemoteFile .
FirewallA set of properties related to firewall access.
LocalFileThe path to a local file for upload/download.
LocalHostThe name of the local host or user-assigned IP interface through which connections are initiated or accepted.
LocalPortThe TCP port in the local host where the class binds.
OperationsThis collection contains all running operations.
OverwriteWhether or not the class should overwrite files during transfer.
RemoteFileThe name of the remote file for uploading, downloading, etc.
RemotePathThe current path in the SSH server.
SSHAcceptServerHostKeyInstructs the class to accept the server host key that matches the supplied key.
SSHAuthModeThe authentication method to be used the class when calling SSHLogon .
SSHCertA certificate to be used for authenticating the SSHUser .
SSHCompressionAlgorithmsA comma-separated list containing all allowable compression algorithms.
SSHEncryptionAlgorithmsA comma-separated list containing all allowable encryption algorithms.
SSHHostThe address of the SSH host.
SSHPasswordThe password for SSH password-based authentication.
SSHPortThe port on the SSH server where the SSH service is running; by default, 22.
SSHUserThe username for SSH authentication.
StartByteThe offset in bytes at which to begin the Upload or Download.
StdinA string of data to be sent to the remote host while connected.
TimeoutA timeout for the class.

Method List


The following is the full list of the methods of the class with short descriptions. Click on the links for further details.

AppendAppend data from a local file; to a remote file using SFTP.
CancelOperationCancels the operation specified by OperationId .
ConfigSets or retrieves a configuration setting.
CreateFileCreates a file on the remote server using SFTP.
DeleteFileDeletes a file on the remote server using SFTP.
DoEventsProcesses events from the internal message queue.
DownloadDownload a RemoteFile using SFTP or SCP.
ExecuteExecute a Command on the remote host.
InterruptInterrupt the current method.
ListDirectoryList the current directory specified by RemotePath on an server using SFTP.
MakeDirectoryCreates a directory on the remote server using SFTP.
RemoveDirectoryRemoves a directory on the remote server using SFTP.
RenameFileChanges the name of a file on the remote server using SFTP.
SetDownloadStreamSets the stream to which the downloaded data from the server will be written.
SetUploadStreamSets the stream from which the class will read data to upload to the server.
SSHLogoffLogoff from the SSH server.
SSHLogonLogon to the SSHHost using the current SSHUser and SSHPassword .
UpdateFileAttributesInstructs the class to send the FileAttributes to the server using SFTP.
UploadUpload a file specified by LocalFile using SCP or SFTP.

Event List


The following is the full list of the events fired by the class with short descriptions. Click on the links for further details.

AppendCompleteFired when an Append operation completes.
ConnectedFired immediately after a connection completes (or fails).
ConnectionStatusFired to indicate changes in connection state.
CreateFileCompleteFired when a CreateFile operation completes (or fails).
DeleteFileCompleteFired when a DeleteFile operation completes (or fails).
DirListFired when a directory entry is received.
DisconnectedFired when a connection is closed.
DownloadCompleteFired when a Download operation completes (or fails).
EndTransferFired when a file completes downloading/uploading.
ErrorInformation about errors during data delivery.
ExecuteCompleteFired when an Execute operation completes (or fails).
ListDirectoryCompleteFired when a ListDirectory operation completes (or fails).
LogFires once for each log message.
MakeDirectoryCompleteFired when a MakeDirectory operation completes (or fails).
RemoveDirectoryCompleteFired when a RemoveDirectory operation completes (or fails).
RenameFileCompleteFired when a RenameFile operation completes (or fails).
SSHCustomAuthFired when the class is doing custom authentication.
SSHKeyboardInteractiveFired when the class receives a request for user input from the server.
SSHServerAuthenticationFired after the server presents its public key to the client.
SSHStatusShows the progress of the secure connection.
StartTransferFired when a file starts downloading/uploading.
StderrFired when data (complete lines) come in through stderr.
StdoutFired when data (complete lines) come in through stdout.
TransferFired during file download/upload.
UpdateFileAttributesCompleteFired when a UpdateFileAttributes operation completes (or fails).
UploadCompleteFired when an Upload operation completes (or fails).

Configuration Settings


The following is a list of configuration settings for the class with short descriptions. Click on the links for further details.

AllowBackslashInNameWhether backslashes are allowed in folder and file names.
AsyncTransferControls whether simultatenous requests are made to read or write files.
AttrAccessTimeCan be queried for the AccessTime file attribute during the DirList event.
AttrCreationTimeCan be queried for the CreationTime file attribute during the DirList event.
AttrFileTypeCan be queried for the FileType file attribute during the DirList event.
AttrGroupIdCan be queried for the GroupId file attribute during the DirList event.
AttrLinkCountCan be queried for the LinkCount file attribute during the DirList event.
AttrOwnerIdCan be queried for the OwnerId file attribute during the DirList event.
AttrPermissionCan be queried for the Permissions file attribute during the DirList event.
CheckFileHashCompares a server-computed hash with a hash calculated locally.
DisableRealPathControls whether or not the SSH_FXP_REALPATH request is sent.
ExcludeFileMaskSpecifies a file mask for excluding files in directory listings.
FileMaskDelimiterSpecifies a delimiter to use for setting multiple file masks in the RemoteFile property.
FiletimeFormatSpecifies the format to use when returning filetime strings.
FreeSpaceThe free space on the remote server in bytes.
GetSpaceInfoQueries the server for drive usage information.
GetSymlinkAttrsWhether to get the attributes of the symbolic link, or the resource pointed to by the link.
IgnoreFileMaskCasingControls whether or not the file mask is case sensitive.
LocalEOLWhen TransferMode is set, this specifies the line ending for the local system.
LogSFTPFileDataWhether SFTP file data is present in Debug logs.
MaskSensitiveMasks passwords in logs.
MaxFileDataSpecifies the maximum payload size of an SFTP packet.
MaxOutstandingPacketsSets the maximum number of simultaneous read or write requests allowed.
NegotiatedProtocolVersionThe negotiated SFTP version.
NormalizeRemotePathWhether to normalize the RemotePath.
PreserveFileTimePreserves the file's timestamps during transfer.
ProtocolVersionThe highest allowable SFTP version to use.
ReadLinkThis settings returns the target of a specified symbolic link.
RealPathControlFlagSpecifies the control-byte field sent in the SSH_FXP_REALPATH request.
RealTimeUploadEnables real time uploading.
RealTimeUploadAgeLimitThe age limit in seconds when using RealTimeUpload.
ServerEOLWhen TransferMode is set, this specifies the line ending for the remote system.
SimultaneousTransferLimitThe maximum number of simultaneous file transfers.
TotalSpaceThe total space on the remote server in bytes.
TransferModeThe transfer mode (ASCII or Binary).
TransferredDataLimitSpecifies the maximum number of bytes to download from the remote file.
UseFxpStatWhether SSH_FXP_STAT is sent.
DirectoryPermissionsThe permissions of folders created on the remote host.
LastAccessedTimeThe last accessed time of the remote file.
LastModifiedTimeThe last modified time of the remote file.
PreserveFileTimePreserves the file's modified time during transfer.
RecursiveModeIf set to true the class will recursively upload or download files.
ServerResponseWindowThe time to wait for a server response in milliseconds.
DisconnectOnChannelCloseWhether to automatically close the connection when a channel is closed.
EncodedTerminalModesThe terminal mode to set when communicating with the SSH host.
FallbackKeyboardAuthWhether to attempt keyboard authorization after another authorization method has failed.
ShellPromptThe character sequence of the prompt on the SSH host to wait for.
StdInFileThe file to use as Stdin data.
StripANSIWhether to remove ANSI escape sequences.
TerminalHeightThe height of the terminal display.
TerminalModesThe terminal mode to set when communicating with the SSH host.
TerminalTypeThe terminal type the class will use when connecting to a server.
TerminalUsePixelWhether the terminal's dimensions are in columns/rows or pixels.
TerminalWidthThe width of the terminal display.
UpdateTerminalSizeUsed to update the terminal size.
DisconnectOnChannelCloseWhether to automatically close the connection when a channel is closed.
EncodedTerminalModesThe terminal mode to set when communicating with the SSH host.
StdInFileThe file to use as Stdin data.
TerminalHeightThe height of the terminal display.
TerminalModesThe terminal mode to set when communicating with the SSH host.
TerminalUsePixelWhether the terminal's dimensions are in columns/rows or pixels.
TerminalWidthThe width of the terminal display.
ClientSSHVersionStringThe SSH version string used by the class.
EnablePageantAuthWhether to use a key stored in Pageant to perform client authentication.
KerberosDelegationIf true, asks for credentials with delegation enabled during authentication.
KerberosRealmThe fully qualified domain name of the Kerberos Realm to use for GSSAPI authentication.
KerberosSPNThe Kerberos Service Principal Name of the SSH host.
KeyRenegotiationThresholdSets the threshold for the SSH Key Renegotiation.
LogLevelSpecifies the level of detail that is logged.
MaxPacketSizeThe maximum packet size of the channel, in bytes.
MaxWindowSizeThe maximum window size allowed for the channel, in bytes.
PasswordPromptThe text of the password prompt used in keyboard-interactive authentication.
PreferredDHGroupBitsThe size (in bits) of the preferred modulus (p) to request from the server.
RecordLengthThe length of received data records.
ServerSSHVersionStringThe remote host's SSH version string.
SignedSSHCertThe CA signed client public key used when authenticating.
SSHAcceptAnyServerHostKeyIf set the class will accept any key presented by the server.
SSHAcceptServerCAKeyThe CA public key that signed the server's host key.
SSHAcceptServerHostKeyFingerPrintThe fingerprint of the server key to accept.
SSHFingerprintHashAlgorithmThe algorithm used to calculate the fingerprint.
SSHFingerprintMD5The server hostkey's MD5 fingerprint.
SSHFingerprintSHA1The server hostkey's SHA1 fingerprint.
SSHFingerprintSHA256The server hostkey's SHA256 fingerprint.
SSHKeepAliveCountMaxThe maximum number of keep alive packets to send without a response.
SSHKeepAliveIntervalThe interval between keep alive packets.
SSHKeyExchangeAlgorithmsSpecifies the supported key exchange algorithms.
SSHKeyRenegotiateCauses the class to renegotiate the SSH keys.
SSHMacAlgorithmsSpecifies the supported Mac algorithms.
SSHPubKeyAuthSigAlgorithmsSpecifies the enabled signature algorithms that may be used when attempting public key authentication.
SSHPublicKeyAlgorithmsSpecifies the supported public key algorithms.
SSHVersionPatternThe pattern used to match the remote host's version string.
TryAllAvailableAuthMethodsIf set to true, the class will try all available authentication methods.
WaitForChannelCloseWhether to wait for channels to be closed before disconnected.
WaitForServerDisconnectWhether to wait for the server to close the connection.
CloseStreamAfterTransferIf true, the class will close the upload or download stream after the transfer.
ConnectionTimeoutSets a separate timeout value for establishing a connection.
FirewallAutoDetectTells the class whether or not to automatically detect and use firewall system settings, if available.
FirewallHostName or IP address of firewall (optional).
FirewallListenerIf true, the class binds to a SOCKS firewall as a server (IPPort only).
FirewallPasswordPassword to be used if authentication is to be used when connecting through the firewall.
FirewallPortThe TCP port for the FirewallHost;.
FirewallTypeDetermines the type of firewall to connect through.
FirewallUserA user name if authentication is to be used connecting through a firewall.
KeepAliveIntervalThe retry interval, in milliseconds, to be used when a TCP keep-alive packet is sent and no response is received.
KeepAliveTimeThe inactivity time in milliseconds before a TCP keep-alive packet is sent.
LingerWhen set to True, connections are terminated gracefully.
LingerTimeTime in seconds to have the connection linger.
LocalHostThe name of the local host through which connections are initiated or accepted.
LocalPortThe port in the local host where the class binds.
MaxLineLengthThe maximum amount of data to accumulate when no EOL is found.
MaxTransferRateThe transfer rate limit in bytes per second.
ProxyExceptionsListA semicolon separated list of hosts and IPs to bypass when using a proxy.
TCPKeepAliveDetermines whether or not the keep alive socket option is enabled.
TcpNoDelayWhether or not to delay when sending packets.
UseIPv6Whether to use IPv6.
UseNTLMv2Whether to use NTLM V2.
AbsoluteTimeoutDetermines whether timeouts are inactivity timeouts or absolute timeouts.
FirewallDataUsed to send extra data to the firewall.
InBufferSizeThe size in bytes of the incoming queue of the socket.
OutBufferSizeThe size in bytes of the outgoing queue of the socket.
BuildInfoInformation about the product's build.
GUIAvailableTells the class whether or not a message loop is available for processing events.
LicenseInfoInformation about the current license.
UseDaemonThreadsWhether threads created by the class are daemon threads.
UseInternalSecurityAPITells the class whether or not to use the system security libraries or an internal implementation.

Copyright (c) 2023 /n software inc. - All rights reserved.
IPWorks SSH 2020 Java Edition - Version 20.0 [Build 8501]