C# application


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 its StandardInput, 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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值