'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 [email protected]
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 ?
Solution 1:[1]
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");
Solution 2:[2]
the Console.ReadKey(); should be placed in using block to ensure the SshClient instance is not disposed.
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();
}
}
Solution 3:[3]
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 another way to keep the SSH tunnel up (instead of a Sleep + recursive call every 8 hours).
Posted on behalf of the question asker
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | faby |
Solution 2 | Lingreate |
Solution 3 |