【问题标题】:How i can establish connection ssh from c#我如何从 c# 建立连接 ssh
【发布时间】:2016-07-14 13:26:50
【问题描述】:

这是我在stackoverflow上的第一篇文章,对不起。

在我的范围内:

private SshClient client;
private ForwardedPortDynamic port;

我有一个示例代码可以与 putty 类似的 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;
        }
    }

我有一个按钮可以调用方法“Connect()”,但一段时间后它会断开连接并且不再工作。是什么导致断开连接?我需要在不确定的时间内建立连接。

非常感谢!

【问题讨论】:

  • 嗨,杰克,你有示例代码吗?

标签: c# ssh proxy tunneling


【解决方案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);
    ...
}

第二,你有没有看过this建议你需要使用ForwardedPortLocal而不是ForwardedPortDynamic

【讨论】:

    【解决方案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 设置为 30s 会有所帮助?

    【讨论】:

    • 如果我这样做,我总会有一个新的连接,对吧?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-20
    • 2014-07-25
    • 2015-12-21
    • 2014-07-25
    • 2017-06-24
    • 2017-04-26
    相关资源
    最近更新 更多