2021年1月20日 星期三

php 利用ssh執行遠端或本地liunx伺服器命令

PHP function ssh2_connect is not working

sudo apt-get install php-ssh2 && sudo /etc/init.d/apache2 restart

sudo apt-get install libssh2-php && sudo /etc/init.d/apache2 restart



 function ssh_exec($host, $port = 22, $ssh_username, $ssh_password, $command) {

    $con = ssh2_connect($host, $port);

    $auth_methods = ssh2_auth_none($con, $ssh_username);

    if (in_array('password', $auth_methods)) {

        $auth_methods = ssh2_auth_password($con, $ssh_username, $ssh_password);

    }

    $stdout_stream = ssh2_exec($con, $command);

    $err_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDERR);


    stream_set_blocking($stdout_stream, true); 

    stream_set_blocking($err_stream, true);


    $result_stdout = stream_get_contents($stdout_stream);

    $result_error = stream_get_contents($err_stream);


    fclose($stdout_stream);

    fclose($err_stream);

    return array('result' => $result_stdout, 'error' => $result_error);

}

$result = ssh_exec('172.20.10.11' , 22, 'pi', 'xxx', 'cd /var/www && python3 /var/www/test2.py');

print_r( $result);


資料來源: https://www.itread01.com/content/1549220941.html

沒有留言: