由於缺乏完整的範例,這裡提供一個簡單的 SSH2 類別,用於連線到伺服器、使用公鑰驗證、驗證伺服器的指紋、發出指令並讀取其標準輸出,以及正確斷線。注意:您可能需要確保您的指令會產生輸出,以便提取回應。有些人認為,在您提取回應之前,指令是不會執行的。
<?php
class NiceSSH {
// SSH Host
private $ssh_host = 'myserver.example.com';
// SSH Port
private $ssh_port = 22;
// SSH Server Fingerprint
private $ssh_server_fp = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// SSH Username
private $ssh_auth_user = 'username';
// SSH Public Key File
private $ssh_auth_pub = '/home/username/.ssh/id_rsa.pub';
// SSH Private Key File
private $ssh_auth_priv = '/home/username/.ssh/id_rsa';
// SSH Private Key Passphrase (null == no passphrase)
private $ssh_auth_pass;
// SSH Connection
private $connection;
public function connect() {
if (!($this->connection = ssh2_connect($this->ssh_host, $this->ssh_port))) {
throw new Exception('Cannot connect to server');
}
$fingerprint = ssh2_fingerprint($this->connection, SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);
if (strcmp($this->ssh_server_fp, $fingerprint) !== 0) {
throw new Exception('Unable to verify server identity!');
}
if (!ssh2_auth_pubkey_file($this->connection, $this->ssh_auth_user, $this->ssh_auth_pub, $this->ssh_auth_priv, $this->ssh_auth_pass)) {
throw new Exception('Autentication rejected by server');
}
}
public function exec($cmd) {
if (!($stream = ssh2_exec($this->connection, $cmd))) {
throw new Exception('SSH command failed');
}
stream_set_blocking($stream, true);
$data = "";
while ($buf = fread($stream, 4096)) {
$data .= $buf;
}
fclose($stream);
return $data;
}
public function disconnect() {
$this->exec('echo "EXITING" && exit;');
$this->connection = null;
}
public function __destruct() {
$this->disconnect();
}
}
?>
[php.net 的 danbrown 編輯:包含 AlainC 在 2012 年 6 月 26 日的使用者筆記 #109185(已移除)中建議的兩個錯誤修正。]