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.
-> 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.
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 email@example.com -pw abcd123";
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.