Execute commands on remote machine via PHP

前端 未结 3 628
夕颜
夕颜 2021-02-03 12:11

To give background on my environment:

I have 3 machines A, B & C

A = Webserver, running a php website which basically acts as an interface for B & C

3条回答
  •  花落未央
    2021-02-03 13:01

    Use phpseclib to securely SSH or SCP to remote servers

    Install with composer require phpseclib/phpseclib

    use phpseclib\Crypt\RSA;
    use phpseclib\Net\SSH2;
    use phpseclib\Net\SCP;
    
    // Load your private key
    $key = new RSA();
    $key->loadKey('private key string');
    
    // Connect to the server
    $ssh = new SSH2('ip_address', 'port', 'timeout');
    if (!$ssh->login('username', $key)) {
        throw new Exception("Unable to connect");
    }
    
    // Run a remote command
    echo $ssh->exec('whoami');
    
    // SCP put a string
    $result = (new SCP($ssh))->put('remotePath', 'content to put');
    // SCP put a file
    $result = (new SCP($ssh))->put('remotePath', 'localPath', SCP::SOURCE_LOCAL_FILE);
    
    // SCP get a file
    $result = (new SCP($this->ssh))->get('remotePath', 'localPath');
    
    // $result is true or false
    

提交回复
热议问题