When people think of the Secure Shell (SSH) protocol, interactive terminal sessions and secure file transfers using SFTP are typically what to come to mind. In addition to these common functions, SSH also supports securely executing a command on a remote host and returning the output of that command back to the local system. The SSH component that is included with SocketTools enables you to take advantage of this functionality through a single method call named Execute.
For example, in Visual Basic the code could look like this:
SecureShell.HostName = "remote.server.net" SecureShell.UserName = "username" SecureShell.Password = "password" Dim strResult = SecureShell.Execute("/bin/ps -ef") If strResult.Length = 0 And SecureShell.LastError > 0 Then MessageBox.Show(SecureShell.LastErrorString) Exit Sub End If TextBox1.Text = strResult
In this example, the typical property values are set for the SSH server domain name or IP address, the user name and password required to authenticate the session. The Execute method is then called, providing the command to execute as a parameter, and the output from the command will be returned to a string value. In this case, we’re connecting to a UNIX based system and listing all of the running processes using the /bin/ps command.
If an error occurs, then the return value will be an empty string and the LastError property will be set to a value which identifies the error condition. In this case, we simply display a message box that shows a human-readable description of the last error code and then exit the subroutine.
As with an interactive terminal session, the entire operation is encrypted over the network, including the command that is sent and the output that it returns. For this reason, using SSH is preferred over the old rexec protocol which would send both the user credentials and the command as plain text. If you’re currently using the Remote Command class in your applications, it’s recommended that you consider rewriting your code to use the SSH component as a secure alternative.