使用SSH.net进行C#SSH端口转发

问题描述 投票:0回答:2

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

ssh -NfD 1080 [email protected]

这是我制作的代码:

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#程序连接的服务器。任何的想法 ?

编辑:

我在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小时一次Sleep +递归调用)。希望它可以帮助某人。谢谢你!

c# .net ssh
2个回答
0
投票

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

client.RunCommand("some command");

0
投票

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();
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.