前段时间我不得不找到一种方法来为内部 Web 开发服务器制作一个自定义控制面板,我环顾四周,发现有一个用于 PHP 的 SSH 包,它通常带有 ssh。您可能想尝试一下:)
您必须在您的服务器上生成一个密钥,以允许您的服务器无需密码即可连接到目标,为此:
ssh-keygen -t rsa
ssh-copy-id root@targetmachine
在网上查找有关 RSA 密钥生成的更多信息,网上有很多信息。然后,只要做一个像这样的小函数,你就可以执行大量的命令了 :)
<?php
/**
*
* Runs several SSH2 commands on the devl server as root
*
*/
function ssh2Run(array $commands){
$connection = ssh2_connect('localhost');
$hostkey = ssh2_fingerprint($connection);
ssh2_auth_pubkey_file($connection, 'root', '/home/youruser/.ssh/id_rsa.pub', '/home/youruser/.ssh/id_rsa');
$log = array();
foreach($commands as $command){
// Run a command that will probably write to stderr (unless you have a folder named /hom)
$log[] = 'Sending command: '.$command;
$log[] = '--------------------------------------------------------';
$stream = ssh2_exec($connection, $command);
$errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
// Enable blocking for both streams
stream_set_blocking($errorStream, true);
stream_set_blocking($stream, true);
// Whichever of the two below commands is listed first will receive its appropriate output. The second command receives nothing
$log[] = 'Output of command:';
$log[] = stream_get_contents($stream);
$log[] = '--------------------------------------------------------';
$error = stream_get_contents($errorStream);
if(strlen($error) > 0){
$log[] = 'Error occured:';
$log[] = $error;
$log[] = '------------------------------------------------';
}
// Close the streams
fclose($errorStream);
fclose($stream);
}
//Return the log
return $log;
}
此外,您可能会对 SSH2 for php 的文档感兴趣:http: //ca3.php.net/manual/fr/book.ssh2.php