Execute commands on remote machine via PHP

前端 未结 3 623
夕颜
夕颜 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 12:52

    I recommend SSH2 to execute commands on remote machine. You can use pecl to install it easily. After that, you may use ssh2_exec() function to execute your commands and ssh2_fetch_stream() function to get stderr. Example codes are listed below:

    // start connection
    $connection = ssh2_connect("your remote ip address", your port);
    ssh2_auth_password($connection,"your user name","your passwd");
    
    // connection established, start to execute codes
    $stream = ssh2_exec($connection, "your command");  
    $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
    
    // block 2 streams simutaneously
    stream_set_blocking($errorStream, true);
    stream_set_blocking($stream,true);
    
    // write stdout and stderr to log file
    file_put_contents("your log file-path", date('Y-m-d H:i:s')."\nError: ".stream_get_contents($errorStream)."\nOutput: ".stream_get_contents($stream), FILE_APPEND)
    
    // close 2 streams   
    fclose($errorStream);
    fclose($stream);
    
    // close remote connection
    ssh2_exec($connection, 'exit');
    

    Cheers.

提交回复
热议问题