2013年2月24日星期日

CREATING A SSH CONNECTION USING 'PLINK' (PUTTY) VIA C# APPLICATION



What is 'plink'? 
Its a command-line SSH connection method provided by PuTTY
Lets say, you have an application running on windows platform and this application needs to connect to a DB residing on some other platform like Linux, via SSH connection. And you don't want to manually go and establish the PuTTY connection for each time you want to run your application, just for the sake of connecting to the DB. This would really become a headless job. 
For this reason we can use 'plink' which is a command-line application basically used for automated applications.

plink
-> Press 'y' and enter. After that it might show some welcome message and the 'Last login' message. Now you have established your SSH connection. 

How to establish this plink connection from your application using C#? 
You first need to open the command prompt using the 'Process' class and then in itsStandardInput, provide the plink command-line. After the connection is set, run your business logic and after its done write "logout" to the StandardInput which ends your SSH connection.

>>Code:-
public void EstablishSshConnection() 

    ProcessStartInfo psi = new ProcessStartInfo(@"C:\Windows\System32\cmd"); 
    psi.RedirectStandardInput = true; 
    psi.RedirectStandardOutput = true; 
    psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal; 
    psi.UseShellExecute = false; 
    psi.CreateNoWindow = false;
 
    Process process = Process.Start(psi); 
    string cmdForTunnel = "plink -L 8888:localhost:3306 test@mindfiresolutions.com -pw abcd123"; 
    process.StandardInput.WriteLine(cmdForTunnel); 
    process.WaitForExit(); 
    Thread.Sleep(10000);

    DoBusinessLogic(); 
    process.StandardInput.WriteLine("logout"); 
    Thread.Sleep(10000);

    if (process.HasExited) 
    
        process.Close(); 
        process.Dispose(); 
    
}

Remember to sync the command prompt's directory path with the plink.exe file's path. When you open the command prompt using C# code, the default directory path is set to "C:\Windows\System32" as in some Windows OS (Windows 7). So, in that case you need to place the plink.exe file in "C:\Windows\System32" folder or else the plink command-line won't execute.

Related Tags:

plink, putty, C Sharp, .NET, SSH
Author: Richi Padhi 

没有评论:

发表评论