我如何从C#建立连接SSH [英] How i can establish connection ssh from c#

查看:713
本文介绍了我如何从C#建立连接SSH的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我关于stackoverflow的第一篇文章,对不起.

This is my first post on stackoverflow, sorry for anything.

在我的范围内:

private SshClient client;
private ForwardedPortDynamic port;

我有一个与腻子类似的ssh连接的示例代码:

I have a sample code to connect with ssh similar at putty:

private void Connect()
    {
        try
        {
            client = new SshClient("myserverproxy.net", "user", "password");
            client.KeepAliveInterval = new TimeSpan(0, 0, 60);
            client.ConnectionInfo.Timeout = new TimeSpan(0, 0, 20);
            client.Connect();
            port = new ForwardedPortDynamic("127.0.0.1", 20141);
            client.AddForwardedPort(port);
            port.Exception += delegate(object sender, ExceptionEventArgs e)
            {
                Console.WriteLine(e.Exception.ToString());
            };
            port.Start();
        }
        catch (Exception)
        {
            throw;
        }
    }

此代码将断开连接:

private void Disconnect()
    {
        try
        {
            port.Stop();
            client.Disconnect();
        }
        catch (Exception)
        {

            throw;
        }
    }

我有一个按钮来调用方法"Connect()",但是一段时间后它断开连接,不再起作用.是什么导致断开连接?我需要在不确定的时间内建立连接.

I have a button to call method "Connect()", but after some time it disconnect and don't work anymore. What is causing the disconnect? I need establish connect for undetermined time.

非常感谢!

推荐答案

我无法尝试此操作,但我可以通过以下方式进行操作:

I can't try this but I would do it in this way:

public static void Start()
{
      using (var client = new SshClient("myserverproxy.net", "user", "password"))
      {
           client.KeepAliveInterval = new TimeSpan(0, 0, 60);
           client.ConnectionInfo.Timeout = new TimeSpan(0, 0, 20);
           client.Connect();
           ForwardedPortDynamic port = new ForwardedPortDynamic("127.0.0.1", 20141);
           client.AddForwardedPort(port);
           port.Exception += delegate(object sender, ExceptionEventArgs e)
           {
                Console.WriteLine(e.Exception.ToString());
           };
           port.Start();
     }
}

public static void Main(string[] args)
{
     Thread thread1 = new Thread(Start);
     thread1.Start();
}

也许将KeepAliveInterval设置为30s会有所帮助?

Maybe it helps to set KeepAliveInterval to 30s?

这篇关于我如何从C#建立连接SSH的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆