July 26, 2010

SSH SendReqExec — Interactive Commands such as “more”

Filed under: SSH — Tags: — admin @ 9:41 am

Commands that assume an interactive user at a shell prompt should not be passed to SendRequestExec.  For example, the “more” command assumes there is a shell and that the user will press RETURN when another screenful of text is wanted.  It would be more appropriate to use the Unix/Linux “cat” command w/ SendRequestExec.

To run interactive commands, one should instead start a remote shell by (1) starting a pseudo-terminal by calling SendReqPty and then (2) starting a shell by calling SendReqShell. See this example:

ASP: SSH — Running Commands that Prompt for Additional Input, such as “su”
SQL Server: SSH — Running Commands that Prompt for Additional Input, such as “su”
C#: SSH — Running Commands that Prompt for Additional Input, such as “su”
Delphi: SSH — Running Commands that Prompt for Additional Input, such as “su”
Visual FoxPro: SSH — Running Commands that Prompt for Additional Input, such as “su”
PHP: SSH — Running Commands that Prompt for Additional Input, such as “su”
VB.NET: SSH — Running Commands that Prompt for Additional Input, such as “su”
Visual Basic: SSH — Running Commands that Prompt for Additional Input, such as “su”
VBScript: SSH — Running Commands that Prompt for Additional Input, such as “su”

SSH SendReqExec — Commands with No Output

Filed under: SSH — Tags: — admin @ 9:33 am

When a command is passed to SendReqExec that produces no output, such as “echo 1 > test.txt”, then do not try to read the channel (such as by calling ChannelReadAndPoll) because no data will be forthcoming and the channel read will timeout (as expected). The correct sequence of method calls would be to:

  1. Call SendReqExec to execute the command on the remote server.
  2. Call ChannelSendClose to initiate the closing of the channel.
  3. Call ChannelReceiveToClose to wait until the server closes the channel. In this case, no actual output data is returned because the command passed to SendReqExec produces no output.  This method is called to cleanly wait for the server’s “close” message.

    February 5, 2010

    SSH / SFTP - Too much time between connect and authentication

    Filed under: SFTP, SSH, error messages — Tags: , , , , — admin @ 6:28 am

    The Solution:

    Issue solved.   The problem was, that we stepped through the code and because of that too much time elapsed between connect and authentication.  As we ran the program without breakpoints it worked.

    The Problem:

    The AuthenticatePw method failed and the LastErrorText contained this information:

    ChilkatLog:
       AuthenticatePw:
         DllDate: Jan 31 2010
         UnlockPrefix: ***
         Username: ***
         Component: .NET 2.0
         SshVersion: SSH-2.0-XFB.Gateway Windows
         SftpVersion: 0
         login: ***
         sendMessage:
           msgName: SERVICE_REQUEST
           unpaddedLength: 22
           remainder: 6
           paddingLen: 10
           totalSize: 32
         SentServiceReq: ssh-userauth
         numBytesRequested: 16
         Connection closed by server.
         Failed to read data on SSH connection.
         Failed to read packet from SSH server.
         Error reading service accept.
         Socket connection lost.
         Failed.
    

    December 14, 2009

    Very simple C# SSH Shell Console Terminal

    Filed under: SSH — Tags: , , , , — admin @ 2:48 pm

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

    October 7, 2009

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

    Filed under: SSH, SSH keys — Tags: , , , , — admin @ 6:23 am

    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)

    October 1, 2009

    su Supported by Chilkat SSH for Linux/Unix Servers?

    Filed under: SSH — Tags: — admin @ 7:32 am

    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.

    September 15, 2009

    SFTP and SSH: Separate Connections Required?

    Filed under: SFTP, SSH — Tags: , — admin @ 6:21 pm

    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.

    September 14, 2009

    F-SECURE SSH/SFTP Servers Require Client Identifier to be PuTTY?

    Filed under: SFTP, SSH — Tags: , — admin @ 2:44 pm

    We’ve discovered that F-SECURE SSH/SFTP servers will disconnect during authentication if the SSH client identifier is “SSH-2.0-ChilkatSSH_2.0.0″. This may be overridden by setting the ClientIdentifier property to mimic PuTTY by using a string such as: “SSH-2.0-PuTTY_Local:_May_15_2009_16:25:24″

    March 18, 2009

    SSH: Failed to read 1st key exchange packet

    Filed under: SSH, error messages — Tags: , — admin @ 7:18 am

    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.

    February 13, 2009

    SSH Tunneling (Port Forwarding)

    Filed under: SSH, SSH Tunnel — Tags: , , , — admin @ 10:10 am

    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
    Newer Posts »