要通过SSH2实现PHP的远程命令执行,首先需要安装SSH2扩展。然后可以使用以下代码来实现:
<?php// 连接远程服务器$connection = ssh2_connect('hostname', 22);// 使用用户名和密码进行认证ssh2_auth_password($connection, 'username', 'password');// 执行远程命令$command = 'ls -l';$stream = ssh2_exec($connection, $command);// 读取命令输出stream_set_blocking($stream, true);$output = stream_get_contents($stream);// 关闭连接fclose($stream);// 输出命令执行结果echo $output;?>在上面的代码中,我们首先使用ssh2_connect函数连接到远程服务器,然后使用ssh2_auth_password函数进行认证。接着使用ssh2_exec函数执行远程命令,并通过stream_get_contents函数读取命令输出。最后关闭连接并输出命令执行结果。
请注意,为了安全起见,建议在实际应用中使用SSH密钥进行认证,而不是使用密码。


