Search code examples
sshchainingphpseclib

SSH chaining using PHPSeclib (ssh machine 1, machine 1->machine2, interact)


We've brought up this topic before, but curious if anyone has any new information on this issue.

We use multiple servers that are accessed behind a "management server", so when we SSH in we have to log in there first, then from there log into our destination machine so always at least 2 SSH connections. We currently use port forwarding on the management server by using : which will take us directly through to the server of interest behind the scenes so we think we're directly ssh'ing into each one.

The issue here is that it requires specific setup, and in a scalable environment where servers can be added/removed the maintenance is cumbersome. Ideally we'd just be able to ssh into multiple machines using phpseclib and run commands.

Has anyone ran into this or have advice on a solution from the scripting level? Basically we need to ssh chain and ssh into machine 1, then machine 2 from machine 1, and run commands/interact with machine 2.


Solution

  • $ssh = new Net_SSH2('machine1');
    $ssh->login('user', 'pass');
    
    $ssh->setTimeout(10);    
    $ssh->enablePTY();
    
    $ssh->exec('ssh machine2');
    echo $ssh->read();
    

    At this point (assuming that you're using RSA authentication and that your private key is in your ~/.ssh/id_rsa file on machine) the prompt that you get back should be of machine 2.

    You could connect to a machine3 as well by doing this:

    $ssh = new Net_SSH2('machine1');
    $ssh->login('user', 'pass');
    
    $ssh->setTimeout(10);
    $ssh->enablePTY();
    
    $ssh->exec('ssh machine2');
    echo $ssh->read();
    
    $ssh->exec('ssh machine3');
    echo $ssh->read();