1

I have a target computer which can be accessed only with SSH, I do not have a direct connection, so I need to connect through another SSH machine.

Until now, I connect with putty (SSH) to machine A and then when I am logged in I SSH the machine B.

I'm trying to create an application that will run a script in machine B and I use SSH.NET, here is my code:

using (var client = new SshClient("hostMachineA", "usernameMachineA", "passwordMachineA"))
{
    client.Connect();
    try
    {
        if (client.IsConnected)
        {
            using (var terminalConnection = new SshClient("hostMachineB", "usernameMachineB", "passwordMachineB"))
            {
                terminalConnection.Connect();
                var command = terminalConnection.CreateCommand("ls -ltr");
                command.Execute();
                MessageBox.Show(command.Result);
                terminalConnection.Disconnect();
            }
        }

        client.Disconnect();
    }
    catch (Exception command)
    {
        MessageBox.Show(command.Message);
    }
}     

The problem is that my application connects to Machine A but it cannot establish connection with Machine B, it tries to create a new connection not using the connection which is already established from Machine A.

Any idea?

14
  • The second using is just trying to connect to machine B directly, which you stated you cannot do. You need to tell your client object to connect to machine B instead of going directly for it Commented Mar 19, 2019 at 11:36
  • "You need to tell your client object to connect to machine B instead of going directly for it" how can I do that? Commented Mar 19, 2019 at 11:38
  • You are probably port forwarding from A to B and need to do the same thing. This is old but still might help - stackoverflow.com/questions/2835646/net-ssh-port-forwarding Commented Mar 19, 2019 at 11:38
  • Just like you would do it on your command line, so something along the lines of var command = client.CreateCommand("ssh id@server"); and then execute that. There might be an alternative although I'm not very experienced with ssh.net Commented Mar 19, 2019 at 11:41
  • 1
    Guys, indeed issue solved with port forwarding, thank you all! Commented Mar 19, 2019 at 12:28

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.