Very simple C# SSH Shell Console Terminal

Here’s an example that demonstrates a rough start to creating a C# console SSH shell terminal (where the user can type commands and output from the remote command echos to the console:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace SshTerminalConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            Chilkat.Ssh ssh = new Chilkat.Ssh();
            ssh.UnlockComponent("Test");

            //  Hostname may be an IP address or hostname:
            string hostname = "192.168.1.117";
            int port = 22;

            Console.WriteLine("Connecting...");

            //ssh.KeepSessionLog = true;
            bool success = ssh.Connect(hostname, port);
            if (success != true)
            {
                Console.WriteLine(ssh.LastErrorText + "\r\n");
                // Read so we can see the error before the console closes.
                string x = Console.ReadLine();      
                return;
            }

            //  When reading, if no additional data arrives for more than
            //  5 seconds, then abort:
            ssh.IdleTimeoutMs = 5000;

            Console.WriteLine("Authenticating...");

            //  SSH Server Authentication
            //  If there is no login/password required, you must still call
            //  AuthenticatePw and use any values for login/password.
            success = ssh.AuthenticatePw("chilkat", "***");
            if (success != true)
            {
                Console.WriteLine(ssh.LastErrorText + "\r\n");
                // Read so we can see the error before the console closes.
                string x = Console.ReadLine();
                return;
            }

            Console.WriteLine("Opening Channel...");

            //  Open a session channel.
            int channelNum = ssh.OpenSessionChannel();
            if (channelNum < 0)
            {
                Console.WriteLine(ssh.LastErrorText + "\r\n");
                // Read so we can see the error before the console closes.
                string x = Console.ReadLine();
                return;
            }

            //  Request a pseudo-terminal
            string termType;
            termType = "dumb";
            int widthInChars;
            widthInChars = 120;
            int heightInChars;
            heightInChars = 40;
            int pixWidth;
            pixWidth = 0;
            int pixHeight;
            pixHeight = 0;
            success = ssh.SendReqPty(channelNum, termType, widthInChars, heightInChars, pixWidth, pixHeight);
            if (success != true)
            {
                Console.WriteLine(ssh.LastErrorText + "\r\n");
                // Read so we can see the error before the console closes.
                string x = Console.ReadLine();
                return;
            }

            Console.WriteLine("Starting a shell...");

            //  Start a shell on the channel:
            success = ssh.SendReqShell(channelNum);
            if (success != true)
            {
                Console.WriteLine(ssh.LastErrorText + "\r\n");
                // Read so we can see the error before the console closes.
                string x = Console.ReadLine();
                return;
            }

            // Loop to read from the SSH channel, output to the console, and read keyboard input from the console.
            StringBuilder sb = new StringBuilder();
            while (true)
            {
                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo key = Console.ReadKey(true);
                    Console.Write(key.KeyChar);

                    switch (key.Key)
                    {
                        case ConsoleKey.Enter:
                            Console.WriteLine("");

                            sb.Append("\n");
                            success = ssh.ChannelSendString(channelNum, sb.ToString(), "ansi");
                            if (success != true)
                            {
                                Console.WriteLine(ssh.LastErrorText + "\r\n");
                                // Read so we can see the error before the console closes.
                                string x = Console.ReadLine();
                                return;
                            }

                            sb.Length = 0;
                            break;
                        default:
                            //Console.Write(key.KeyChar);
                            sb.Append(key.KeyChar);
                            break;
                    }

                }

                // Now check for incoming data from the SSH channel.
                int retval = ssh.ChannelPoll(channelNum, 10);
                if (retval == -1)
                {
                    Console.Write(ssh.LastErrorText);
                    Console.WriteLine("");
                    // Read so we can see the error before the console closes.
                    string x = Console.ReadLine();
                    return;
                }
                if (retval > 0)
                {
                    Console.Write(ssh.GetReceivedText(channelNum, "ansi"));
                }
                else
                {
                    // If data arrived, loop around and get more immediately.
                    // Otherwise wait 20ms.
                    System.Threading.Thread.Sleep(20);
                }

            }  

        }
    }
}

Converting a PuTTY Private Key (.ppk) to OpenSSH (.pem)

ASP: Convert PuTTY Private Key (ppk) to OpenSSH (pem)
SQL Server: Convert PuTTY Private Key (ppk) to OpenSSH (pem)
C#: Convert PuTTY Private Key (ppk) to OpenSSH (pem)
C++: Convert PuTTY Private Key (ppk) to OpenSSH (pem)
MFC: Convert PuTTY Private Key (ppk) to OpenSSH (pem)
C: Convert PuTTY Private Key (ppk) to OpenSSH (pem)
Delphi: Convert PuTTY Private Key (ppk) to OpenSSH (pem)
Visual FoxPro: Convert PuTTY Private Key (ppk) to OpenSSH (pem)
Java: Convert PuTTY Private Key (ppk) to OpenSSH (pem)
Perl: Convert PuTTY Private Key (ppk) to OpenSSH (pem)
PHP: Convert PuTTY Private Key (ppk) to OpenSSH (pem)
Python: Convert PuTTY Private Key (ppk) to OpenSSH (pem)
Ruby: Convert PuTTY Private Key (ppk) to OpenSSH (pem)
VB.NET: Convert PuTTY Private Key (ppk) to OpenSSH (pem)
Visual Basic: Convert PuTTY Private Key (ppk) to OpenSSH (pem)
VBScript: Convert PuTTY Private Key (ppk) to OpenSSH (pem)

su Supported by Chilkat SSH for Linux/Unix Servers?

Question:

I don’t see anything in the documentation or examples to indicate that “su” is supported w/ SSH?  Is it possible to login to a user account and then “su” to root?

Answer:

“su” is a command just like any other Unix/Linux command. It is typed at the command prompt, it does something, and a response is written to standard output (possibly nothing more than new command prompt). Therefore, any example you see for starting a remote shell and running commands would apply with “su”.

To put it simply: Yes, “su” is supported because it’s a command just like “ls”, “cat”, etc.

SFTP and SSH: Separate Connections Required?

Question:

I have an application using your code that does several SSH and SFTP command during processing. Can I just establish a connection, authenticate passwords and the other setup steps once and then use that connection throughout the program or do I need to perform these steps in every function? If I can do I need a separate connection for SFTP and for SSH?

Answer:

You’ll need one connection for SFTP, and one connection for SSH.  So  you need to have one instance of an SFTP object and one instance of the SSH object.   Therefore, you have two connections (one in each object).

You should be able to maintain those connections.  With SSH, you may open and close logical channels.  In fact, you may have any number of logical channels open simultaneously on the same connection.   With SFTP, you may upload and download any number of files on the same connection.

One thing to beware of, and this usually applies to any client-server protocol, is that if the client becomes inactive for some period of time the server may decide to close the connection.  This time limit is entirely up to the server and the client has no control over it.  Therefore, you might have  your application periodically send a “no-op” message to the server when it is inactive.  With SSH, you would do it by calling SendIgnore.  With SFTP you might call RealPath(“.”,””)  just for the sake of generating traffic.

However, even with the “no-op” strategy, your application should still be able to handle the chance that the server may disconnect, or you may lose the connection for some external reason, at any time.

SSH: Failed to read 1st key exchange packet

Here’s an explanation for the following error message:

    Established TCP/IP connection with SSH server
    FromServer: SSH-1.5-Cisco-1.25
    numBytesRequested: 8
    Connection closed by server.
    Failed to read data on SSH connection.
    Failed to read 1st key exchange packet
    Failed.

The error message indicates that as soon as the TCP/IP socket connection was accepted
by the SSH server, it then decided to disconnect. No data was exchanged over the socket connection. In other words, you didn’t even receive the initial “hello” message.

The SSH server probably rejected the connection based on the IP address from which you’re connecting.

Multiple SSH Tunnels – ODBC Connection

Question:

Hi, I’m extremely interested in purchasing the Chilikat SSH dll. Let
me describe my situation:

I have several host sites (approximately 70 of them) that allow me to
connect to their SSH servers. All of these sites have a database
server (sitting on the same server as the ssh server) accepting
connections on port 1937. I have been successful in connecting to
each site (although one site at a time) using a SSH Port Forwarding
command, however I have to manually enter my SSH password (which is
why I’m looking at automating this using your SSH package). Also, all
of these SSH sites are on different networks with their own subnet.

Instead of connecting to one site at a time, I would like to be able
to connect to all of the sites using your software. That means I
would have multiple SSH tunnels open at once. The problem is, my ODBC
connection doesn’t know which tunnel it’s supposed to go through in
order to connect to the correct database. That’s because I select
‘127.0.0.1’ as the DB server in the SSH connection command, but how
does that ODBC connection know which tunnel I want it to use?

I thought maybe I could specify the source port in the SSH connection
and then when I use a ODBC connection string, I would be able to
select the source port that goes with the database that I’m connecting
to. However, I haven’t found anything about selecting the source port
in an ODBC connection string (only the destination port).

So my question is, is there any way I can use your SSH package to open
multiple SSH connections and then use an odbc connection string to
acess the correct tunnel?

Answer:

Yes, it’s possible, and it’s very easy.

When the SSH Tunnel thread accepts a new connection, it uses the current
value of the DestPort and DestHostname properties for the destination
database server. Therefore, before each connection is established,
change the DestPort and DestHostname properties to the correct database
server. Your solution would involve 2 background threads, both of which
are completely managed by the SshTunnel class: a background thread for
accepting new connections, and a background thread for managing all
existing tunnels.

SSH Tunneling (Port Forwarding)

SSH Port Forwarding (or tunneling) allows you to tunnel any TCP connection through an SSH server. For example, consider a database connection:

A direct TCP connection:

DbClient <----TCP---->  DbServer

An SSH tunneled connection:

DbClient <----TCP----> SshClient <====SSH====> SshServer <----TCP----> DbServer

In a tunneled connection, the application connects through an SshClient to an SSH server and starts a direct-tcpip channel, specifying the destination host:port (i.e. the database server). Historically, the SshClient has been a standalone program, such as PuTTY, that typically runs on the same computer as the DbClient. We’ll show you later in this article how the SshClient is merged directly into your application to eliminate the need for a standalone SSH go-between to be running wherever your application runs. This is the power of Chilkat SSH tunneling: your application can create tunnels without requiring external software such as PuTTY to be installed and running.

The SSH Server may run on the same computer as the DbServer, or anywhere else. The typical situation is that both the SSH server and database server are within the same firewall. The firewall typically allows traffic to pass through port 22 to the SSH server, but not to the database server. Communications between the SSH server and database server are not secure, but since they occur behind a firewall, it’s not a problem.

A tunnel can be established to anything, not just a database server. For example:

HttpClient <----TCP----> SshClient <====SSH====> SshServer <----TCP----> HTTP Web Server
SmtpClient <----TCP----> SshClient <====SSH====> SshServer <----TCP----> SMTP Email Server
Pop3Client <----TCP----> SshClient <====SSH====> SshServer <----TCP----> POP3 Email Server
ImapClient <----TCP----> SshClient <====SSH====> SshServer <----TCP----> IMAP Email Server
TcpClient <----TCP----> SshClient <====SSH====> SshServer <----TCP----> Custom TCP Socket Application

Prior to Chilkat, SSH tunneling required a separate client-side program (or Windows Service) to serve as the SSH2 port forwarding client. (This is the SshClient in the diagram above.) This is an added piece of infrastructure that must be installed and running in order for your application to use SSH tunneling. This adds complexity to your application’s deployment, is a potential source of failure, and represents a hidden cost of ongoing support for your application. (Chilkat always recommends minimizing infrastructure and complexity.)

Chilkat provides three solutions to merge the SshClient directly into your application:

  1. Integration with the protocol API. Chilkat’s API’s for SMTP, POP3, and IMAP have been extended with SSH tunneling methods. Using an SSH tunnel with these API’s is simple: Establish the SSH tunnel by calling SshTunnel(hostname,port), then authenticate by calling SshAuthenticatePw(login,password). This creates the tunnel, and the remainder of the IMAP, POP3, or SMTP programming is identical to the non SSH-tunnel case. (See the following examples: Integrated POP3 SSH TunnelingIntegrated SMTP SSH Tunneling, Integrated IMAP SSH Tunneling.
  2. Use the Chilkat SshTunnel class/object to create the “SshClient” in a background thread of the application. This is a good solution when using non-Chilkat API’s that require a hostname:port for a connection, such as with database programming (ADO, ODBC, OLE DB, etc.) Your application would instantiate an SshTunnel object, set various properties (SSH server hostname/port, database server hostname/port, SSH login, etc.) then then start the background thread by calling SshTunnel.BeginAccepting. The SshTunnel runs autonomously in a background thread, accepting connections and managing bi-directional SSH tunnels. Here are examples:  Background Thread SSH Tunneling
  3. Use Chilkat SSH to create a direct-tcpip channel via the Ssh.OpenDirectTcpIpChannel method. Your application may then send and receive data through the SSH tunnel by calling various Chilkat SSH send/receive methods. This solution is good for when the destination server is a custom TCP socket server (i.e. it uses a custom application-specific protocol that you’ve designed).  Here are examples: direct-tcpip Port Forwarding

SSH direct-tcpip Port Forwarding (tunneling)

ASP: SSH Tunnel (Port Forwarding via direct-tcpip channel)
SQL Server: SSH Tunnel (Port Forwarding via direct-tcpip channel)
C#: SSH Tunnel (Port Forwarding via direct-tcpip channel)
C++: SSH Tunnel (Port Forwarding via direct-tcpip channel)
MFC: SSH Tunnel (Port Forwarding via direct-tcpip channel)
C: SSH Tunnel (Port Forwarding via direct-tcpip channel)
Delphi: SSH Tunnel (Port Forwarding via direct-tcpip channel)
Visual FoxPro: SSH Tunnel (Port Forwarding via direct-tcpip channel)
Java: SSH Tunnel (Port Forwarding via direct-tcpip channel)
Perl: SSH Tunnel (Port Forwarding via direct-tcpip channel)
PHP: SSH Tunnel (Port Forwarding via direct-tcpip channel)
Python: SSH Tunnel (Port Forwarding via direct-tcpip channel)
Ruby: SSH Tunnel (Port Forwarding via direct-tcpip channel)
VB.NET: SSH Tunnel (Port Forwarding via direct-tcpip channel)
Visual Basic: SSH Tunnel (Port Forwarding via direct-tcpip channel)
VBScript: SSH Tunnel (Port Forwarding via direct-tcpip channel)

SSH – Multiple Commands w/out Reconnect


Question:

Hi, I’m evaluating Chilkat C++ SSH Library for My VC 9.0 Projects.
I have a question: Your examples send only one command.
I want to send several commands without reconnect.
I experimented and found SendReqShell handles multiple commands execution, not SendReqExec.
Can I have a more detailed sample about this?

Answer:
You may call SendReqExec multiple times on the same open channel.