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:ChannelType | Description | Applicable Methods | Applicable 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.
ChannelType | Specifies the Channel Type to be used by the class. |
Command | The command to be sent to the remote host. |
Connected | Triggers a connection or disconnection. |
DirList | Collection of entries resulting in the last directory listing. |
FileAttributes | The attributes of the RemoteFile . |
FileExists | Returns true if the file specified by RemoteFile exists on the remote server. |
FilePermissions | The file permissions for the RemoteFile . |
Firewall | A set of properties related to firewall access. |
LocalFile | The path to a local file for upload/download. |
LocalHost | The name of the local host or user-assigned IP interface through which connections are initiated or accepted. |
LocalPort | The TCP port in the local host where the class binds. |
Operations | This collection contains all running operations. |
Overwrite | Whether or not the class should overwrite files during transfer. |
RemoteFile | The name of the remote file for uploading, downloading, etc. |
RemotePath | The current path in the SSH server. |
SSHAcceptServerHostKey | Instructs the class to accept the server host key that matches the supplied key. |
SSHAuthMode | The authentication method to be used the class when calling SSHLogon . |
SSHCert | A certificate to be used for authenticating the SSHUser . |
SSHCompressionAlgorithms | A comma-separated list containing all allowable compression algorithms. |
SSHEncryptionAlgorithms | A comma-separated list containing all allowable encryption algorithms. |
SSHHost | The address of the SSH host. |
SSHPassword | The password for SSH password-based authentication. |
SSHPort | The port on the SSH server where the SSH service is running; by default, 22. |
SSHUser | The username for SSH authentication. |
StartByte | The offset in bytes at which to begin the Upload or Download. |
Stdin | A string of data to be sent to the remote host while connected. |
Timeout | A 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.
Append | Append data from a local file; to a remote file using SFTP. |
CancelOperation | Cancels the operation specified by OperationId . |
Config | Sets or retrieves a configuration setting. |
CreateFile | Creates a file on the remote server using SFTP. |
DeleteFile | Deletes a file on the remote server using SFTP. |
DoEvents | Processes events from the internal message queue. |
Download | Download a RemoteFile using SFTP or SCP. |
Execute | Execute a Command on the remote host. |
Interrupt | Interrupt the current method. |
ListDirectory | List the current directory specified by RemotePath on an server using SFTP. |
MakeDirectory | Creates a directory on the remote server using SFTP. |
RemoveDirectory | Removes a directory on the remote server using SFTP. |
RenameFile | Changes the name of a file on the remote server using SFTP. |
SetDownloadStream | Sets the stream to which the downloaded data from the server will be written. |
SetUploadStream | Sets the stream from which the class will read data to upload to the server. |
SSHLogoff | Logoff from the SSH server. |
SSHLogon | Logon to the SSHHost using the current SSHUser and SSHPassword . |
UpdateFileAttributes | Instructs the class to send the FileAttributes to the server using SFTP. |
Upload | Upload 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.
AppendComplete | Fired when an Append operation completes. |
Connected | Fired immediately after a connection completes (or fails). |
ConnectionStatus | Fired to indicate changes in connection state. |
CreateFileComplete | Fired when a CreateFile operation completes (or fails). |
DeleteFileComplete | Fired when a DeleteFile operation completes (or fails). |
DirList | Fired when a directory entry is received. |
Disconnected | Fired when a connection is closed. |
DownloadComplete | Fired when a Download operation completes (or fails). |
EndTransfer | Fired when a file completes downloading/uploading. |
Error | Information about errors during data delivery. |
ExecuteComplete | Fired when an Execute operation completes (or fails). |
ListDirectoryComplete | Fired when a ListDirectory operation completes (or fails). |
Log | Fires once for each log message. |
MakeDirectoryComplete | Fired when a MakeDirectory operation completes (or fails). |
RemoveDirectoryComplete | Fired when a RemoveDirectory operation completes (or fails). |
RenameFileComplete | Fired when a RenameFile operation completes (or fails). |
SSHCustomAuth | Fired when the class is doing custom authentication. |
SSHKeyboardInteractive | Fired when the class receives a request for user input from the server. |
SSHServerAuthentication | Fired after the server presents its public key to the client. |
SSHStatus | Shows the progress of the secure connection. |
StartTransfer | Fired when a file starts downloading/uploading. |
Stderr | Fired when data (complete lines) come in through stderr. |
Stdout | Fired when data (complete lines) come in through stdout. |
Transfer | Fired during file download/upload. |
UpdateFileAttributesComplete | Fired when a UpdateFileAttributes operation completes (or fails). |
UploadComplete | Fired 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.
AllowBackslashInName | Whether backslashes are allowed in folder and file names. |
AsyncTransfer | Controls whether simultatenous requests are made to read or write files. |
AttrAccessTime | Can be queried for the AccessTime file attribute during the DirList event. |
AttrCreationTime | Can be queried for the CreationTime file attribute during the DirList event. |
AttrFileType | Can be queried for the FileType file attribute during the DirList event. |
AttrGroupId | Can be queried for the GroupId file attribute during the DirList event. |
AttrLinkCount | Can be queried for the LinkCount file attribute during the DirList event. |
AttrOwnerId | Can be queried for the OwnerId file attribute during the DirList event. |
AttrPermission | Can be queried for the Permissions file attribute during the DirList event. |
CheckFileHash | Compares a server-computed hash with a hash calculated locally. |
DisableRealPath | Controls whether or not the SSH_FXP_REALPATH request is sent. |
ExcludeFileMask | Specifies a file mask for excluding files in directory listings. |
FileMaskDelimiter | Specifies a delimiter to use for setting multiple file masks in the RemoteFile property. |
FiletimeFormat | Specifies the format to use when returning filetime strings. |
FreeSpace | The free space on the remote server in bytes. |
GetSpaceInfo | Queries the server for drive usage information. |
GetSymlinkAttrs | Whether to get the attributes of the symbolic link, or the resource pointed to by the link. |
IgnoreFileMaskCasing | Controls whether or not the file mask is case sensitive. |
LocalEOL | When TransferMode is set, this specifies the line ending for the local system. |
LogSFTPFileData | Whether SFTP file data is present in Debug logs. |
MaskSensitive | Masks passwords in logs. |
MaxFileData | Specifies the maximum payload size of an SFTP packet. |
MaxOutstandingPackets | Sets the maximum number of simultaneous read or write requests allowed. |
NegotiatedProtocolVersion | The negotiated SFTP version. |
NormalizeRemotePath | Whether to normalize the RemotePath. |
PreserveFileTime | Preserves the file's timestamps during transfer. |
ProtocolVersion | The highest allowable SFTP version to use. |
ReadLink | This settings returns the target of a specified symbolic link. |
RealPathControlFlag | Specifies the control-byte field sent in the SSH_FXP_REALPATH request. |
RealTimeUpload | Enables real time uploading. |
RealTimeUploadAgeLimit | The age limit in seconds when using RealTimeUpload. |
ServerEOL | When TransferMode is set, this specifies the line ending for the remote system. |
SimultaneousTransferLimit | The maximum number of simultaneous file transfers. |
TotalSpace | The total space on the remote server in bytes. |
TransferMode | The transfer mode (ASCII or Binary). |
TransferredDataLimit | Specifies the maximum number of bytes to download from the remote file. |
UseFxpStat | Whether SSH_FXP_STAT is sent. |
DirectoryPermissions | The permissions of folders created on the remote host. |
LastAccessedTime | The last accessed time of the remote file. |
LastModifiedTime | The last modified time of the remote file. |
PreserveFileTime | Preserves the file's modified time during transfer. |
RecursiveMode | If set to true the class will recursively upload or download files. |
ServerResponseWindow | The time to wait for a server response in milliseconds. |
DisconnectOnChannelClose | Whether to automatically close the connection when a channel is closed. |
EncodedTerminalModes | The terminal mode to set when communicating with the SSH host. |
FallbackKeyboardAuth | Whether to attempt keyboard authorization after another authorization method has failed. |
ShellPrompt | The character sequence of the prompt on the SSH host to wait for. |
StdInFile | The file to use as Stdin data. |
StripANSI | Whether to remove ANSI escape sequences. |
TerminalHeight | The height of the terminal display. |
TerminalModes | The terminal mode to set when communicating with the SSH host. |
TerminalType | The terminal type the class will use when connecting to a server. |
TerminalUsePixel | Whether the terminal's dimensions are in columns/rows or pixels. |
TerminalWidth | The width of the terminal display. |
UpdateTerminalSize | Used to update the terminal size. |
DisconnectOnChannelClose | Whether to automatically close the connection when a channel is closed. |
EncodedTerminalModes | The terminal mode to set when communicating with the SSH host. |
StdInFile | The file to use as Stdin data. |
TerminalHeight | The height of the terminal display. |
TerminalModes | The terminal mode to set when communicating with the SSH host. |
TerminalUsePixel | Whether the terminal's dimensions are in columns/rows or pixels. |
TerminalWidth | The width of the terminal display. |
ClientSSHVersionString | The SSH version string used by the class. |
EnablePageantAuth | Whether to use a key stored in Pageant to perform client authentication. |
KerberosDelegation | If true, asks for credentials with delegation enabled during authentication. |
KerberosRealm | The fully qualified domain name of the Kerberos Realm to use for GSSAPI authentication. |
KerberosSPN | The Kerberos Service Principal Name of the SSH host. |
KeyRenegotiationThreshold | Sets the threshold for the SSH Key Renegotiation. |
LogLevel | Specifies the level of detail that is logged. |
MaxPacketSize | The maximum packet size of the channel, in bytes. |
MaxWindowSize | The maximum window size allowed for the channel, in bytes. |
PasswordPrompt | The text of the password prompt used in keyboard-interactive authentication. |
PreferredDHGroupBits | The size (in bits) of the preferred modulus (p) to request from the server. |
RecordLength | The length of received data records. |
ServerSSHVersionString | The remote host's SSH version string. |
SignedSSHCert | The CA signed client public key used when authenticating. |
SSHAcceptAnyServerHostKey | If set the class will accept any key presented by the server. |
SSHAcceptServerCAKey | The CA public key that signed the server's host key. |
SSHAcceptServerHostKeyFingerPrint | The fingerprint of the server key to accept. |
SSHFingerprintHashAlgorithm | The algorithm used to calculate the fingerprint. |
SSHFingerprintMD5 | The server hostkey's MD5 fingerprint. |
SSHFingerprintSHA1 | The server hostkey's SHA1 fingerprint. |
SSHFingerprintSHA256 | The server hostkey's SHA256 fingerprint. |
SSHKeepAliveCountMax | The maximum number of keep alive packets to send without a response. |
SSHKeepAliveInterval | The interval between keep alive packets. |
SSHKeyExchangeAlgorithms | Specifies the supported key exchange algorithms. |
SSHKeyRenegotiate | Causes the class to renegotiate the SSH keys. |
SSHMacAlgorithms | Specifies the supported Mac algorithms. |
SSHPubKeyAuthSigAlgorithms | Specifies the enabled signature algorithms that may be used when attempting public key authentication. |
SSHPublicKeyAlgorithms | Specifies the supported public key algorithms. |
SSHVersionPattern | The pattern used to match the remote host's version string. |
TryAllAvailableAuthMethods | If set to true, the class will try all available authentication methods. |
WaitForChannelClose | Whether to wait for channels to be closed before disconnected. |
WaitForServerDisconnect | Whether to wait for the server to close the connection. |
CloseStreamAfterTransfer | If true, the class will close the upload or download stream after the transfer. |
ConnectionTimeout | Sets a separate timeout value for establishing a connection. |
FirewallAutoDetect | Tells the class whether or not to automatically detect and use firewall system settings, if available. |
FirewallHost | Name or IP address of firewall (optional). |
FirewallListener | If true, the class binds to a SOCKS firewall as a server (IPPort only). |
FirewallPassword | Password to be used if authentication is to be used when connecting through the firewall. |
FirewallPort | The TCP port for the FirewallHost;. |
FirewallType | Determines the type of firewall to connect through. |
FirewallUser | A user name if authentication is to be used connecting through a firewall. |
KeepAliveInterval | The retry interval, in milliseconds, to be used when a TCP keep-alive packet is sent and no response is received. |
KeepAliveTime | The inactivity time in milliseconds before a TCP keep-alive packet is sent. |
Linger | When set to True, connections are terminated gracefully. |
LingerTime | Time in seconds to have the connection linger. |
LocalHost | The name of the local host through which connections are initiated or accepted. |
LocalPort | The port in the local host where the class binds. |
MaxLineLength | The maximum amount of data to accumulate when no EOL is found. |
MaxTransferRate | The transfer rate limit in bytes per second. |
ProxyExceptionsList | A semicolon separated list of hosts and IPs to bypass when using a proxy. |
TCPKeepAlive | Determines whether or not the keep alive socket option is enabled. |
TcpNoDelay | Whether or not to delay when sending packets. |
UseIPv6 | Whether to use IPv6. |
UseNTLMv2 | Whether to use NTLM V2. |
AbsoluteTimeout | Determines whether timeouts are inactivity timeouts or absolute timeouts. |
FirewallData | Used to send extra data to the firewall. |
InBufferSize | The size in bytes of the incoming queue of the socket. |
OutBufferSize | The size in bytes of the outgoing queue of the socket. |
BuildInfo | Information about the product's build. |
GUIAvailable | Tells the class whether or not a message loop is available for processing events. |
LicenseInfo | Information about the current license. |
UseDaemonThreads | Whether threads created by the class are daemon threads. |
UseInternalSecurityAPI | Tells the class whether or not to use the system security libraries or an internal implementation. |