Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

.net - C# SSH port forwarding with SSH.net

I'm trying to do the following thing in a C# program with SSH.NET :

ssh -NfD 1080 username@remote.com

Here's the code I produced :

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();

I connect to an OpenVPN server through this tunnel. When I use the command line it works fine, but when I use the C# program it's like the tunnel isn't working, even if I can send commands to the server I'm connected to through the C# program. Any idea ?

EDIT :

I found an answer thanks to da_rinkes on SSH.NET forum (link).

I was using ForwardedPortLocal instead of ForwardedPortDynamic (-D option with ssh command).

Here's the new code :

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

Still have to find an other way to keep the SSH tunnel up (instead of a Sleep + recursive call every 8 hours). Hope it helps someone. Thank you faby !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As I suggested in comments I think that you can try to execute your commands with client.RunCommand method in this way

client.RunCommand("some command");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...