-->

我怎么能建立从C#连接SSH(How i can establish connection ssh

2019-09-28 09:33发布

这是我的计算器上的第一篇文章,遗憾的事情。

在我的范围:

private SshClient client;
private ForwardedPortDynamic port;

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

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

我有一个按钮来调用方法“连接()”,但过一段时间后,断开与不工作了。 是什么原因造成的脱节? 我需要建立连接的时间未定。

非常感谢!

Answer 1:

首先SshClient是一次性所以使用被称为需要using关键字。 事情是这样的:

using (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);
    ...
}

其次,有你读这意味着你需要使用ForwardedPortLocal而不是ForwardedPortDynamic



Answer 2:

我不能尝试,但我会做这种方式:

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到30秒?



文章来源: How i can establish connection ssh from c#