【问题标题】:C# SSH port forwarding with SSH.net使用 SSH.net 进行 C# SSH 端口转发
【发布时间】:2015-02-09 19:59:47
【问题描述】:

我正在尝试使用 SSH.NET 在 C# 程序中执行以下操作:

ssh -NfD 1080 用户名@remote.com

这是我生成的代码:

using (var client = new SshClient("remote.com", "username", "password"))
{
    client.Connect();
    var port = new ForwardedPortLocal("localhost", 1080, "remote.com", 1080);
    client.AddForwardedPort(port);

    port.Exception += delegate(object sender, ExceptionEventArgs e)
    {
         Console.WriteLine(e.Exception.ToString());
    };
    port.Start();
}
Console.ReadKey();

我通过此隧道连接到 OpenVPN 服务器。当我使用命令行时它工作正常,但是当我使用 C# 程序时,它就像隧道不起作用,即使我可以通过 C# 程序向我连接的服务器发送命令。 有什么想法吗?

【问题讨论】:

  • 你有什么错误吗?
  • 没有一个。我的程序在 1080 上监听,但我无法使用隧道。
  • 所以Console.WriteLine(e.Exception.ToString()); 永远不会触发?
  • 没有。当我向服务器发送命令时,它可以工作(例如 pwd 将我发送回 /home/username)
  • 你能给我提供一个不起作用的例子吗?

标签: c# .net ssh


【解决方案1】:

感谢 SSH.NET 论坛 (link) 上的 da_rinkes,我找到了答案。

我使用的是 ForwardedPortLocal 而不是 ForwardedPortDynamic(带有 ssh 命令的 -D 选项)。

这是新代码:

public void Start()
{
      using (var client = new SshClient("remote.com", "username", "password"))
      {
           client.KeepAliveInterval = new TimeSpan(0, 0, 30);
           client.ConnectionInfo.Timeout = new TimeSpan(0, 0, 20);
           client.Connect();
           ForwardedPortDynamic port = new ForwardedPortDynamic("127.0.0.1", 1080);
           client.AddForwardedPort(port);
           port.Exception += delegate(object sender, ExceptionEventArgs e)
           {
                Console.WriteLine(e.Exception.ToString());
           };
           port.Start();
           System.Threading.Thread.Sleep(1000 * 60 * 60 * 8);
           port.Stop();
           client.Disconnect();
     }
this.Start();
}

仍然必须找到另一种方法来保持 SSH 隧道正常运行(而不是每 8 小时进行一次睡眠 + 递归调用)。

代表提问者发帖

【讨论】:

    【解决方案2】:

    Console.ReadKey();应该放在 using 块中,以确保 SshClient 实例不被释放。

    static void Main(string[] args)
        {
            using (var client = new SshClient("host", "name", "pwd"))
            {
                client.Connect();
                var port = new ForwardedPortDynamic(7575);
                client.AddForwardedPort(port);
    
                port.Exception += delegate (object sender, ExceptionEventArgs e)
                {
                    Console.WriteLine(e.Exception.ToString());
                };
                port.Start();
                Console.ReadKey();
            }
        }
    

    【讨论】:

      【解决方案3】:

      正如我在 cmets 中所建议的,我认为您可以尝试以这种方式使用client.RunCommand 方法执行您的命令

      client.RunCommand("some command");
      

      【讨论】:

        猜你喜欢
        • 2016-08-22
        • 2018-05-28
        • 2014-12-02
        • 2021-01-28
        • 2015-03-03
        • 2018-07-23
        • 2012-09-24
        • 2012-07-02
        相关资源
        最近更新 更多