C#
C#
Multi-Hop SSH (SSH Through SSH)
See more SSH Examples
Demonstrates connecting to one SSH server through another: Application => ServerSSH1 => ServerSSH2. The ConnectThroughSsh method tunnels the second connection through the first. The technique chains further, so ServerSSH3 and beyond can be reached the same way.
Background: This is the "jump host" or bastion pattern: a gateway server is reachable from outside, and the machines you actually want are only reachable from inside. Each hop authenticates separately with its own credentials, and the result is an ordinary
Ssh object for the far server that happens to be routed through the near one. Any number of connections may be tunneled through a single existing connection, and closing an inner connection leaves the outer one alive for reuse.Chilkat C# Downloads
bool success = false;
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Demonstrates connecting to one SSH server through another (SSH through SSH):
//
// Application => ServerSSH1 => ServerSSH2
//
// Any number of SSH connections may be tunneled through a single existing SSH connection, and
// the technique can be chained further to reach ServerSSH3, ServerSSH4, and so on.
Chilkat.Ssh ssh1 = new Chilkat.Ssh();
// Connect directly to the 1st SSH server.
string hostname = "jump.example.com";
int port = 22;
success = ssh1.Connect(hostname,port);
if (success == false) {
Debug.WriteLine(ssh1.LastErrorText);
return;
}
// Normally you would not hard-code the password in source. You should instead obtain it
// from an interactive prompt, environment variable, or a secrets vault.
string password = "mySshPassword";
success = ssh1.AuthenticatePw("mySshLogin",password);
if (success == false) {
Debug.WriteLine(ssh1.LastErrorText);
return;
}
// Connect through the 1st SSH connection to reach the 2nd SSH server.
Chilkat.Ssh ssh2 = new Chilkat.Ssh();
success = ssh2.ConnectThroughSsh(ssh1,"target.example.com",port);
if (success == false) {
Debug.WriteLine(ssh2.LastErrorText);
return;
}
// The 2nd server has its own credentials.
string password2 = "mySshPassword2";
success = ssh2.AuthenticatePw("mySshLogin2",password2);
if (success == false) {
Debug.WriteLine(ssh2.LastErrorText);
return;
}
// ssh2 is now connected and authenticated, and can be used exactly as if it were connected
// directly. For example, open a session channel to run commands.
int channelNum = ssh2.OpenSessionChannel();
if (channelNum < 0) {
Debug.WriteLine(ssh2.LastErrorText);
return;
}
// ... run commands on ssh2 ...
// Closing ssh2 closes the tunnel through ssh1. The ssh1 connection remains alive and may be
// reused for more connections.
ssh2.Disconnect();
ssh1.Disconnect();