由于缺少完整的示例,以下是一个简单的 SSH2 类,用于连接到服务器、使用公钥身份验证进行身份验证、验证服务器的指纹、发出命令并读取其 STDOUT,以及正确断开连接。注意:您可能需要确保您的命令生成输出,以便可以提取响应。有些人建议在提取响应之前不会执行命令。
<?php
class NiceSSH {
// SSH 主机
private $ssh_host = 'myserver.example.com';
// SSH 端口
private $ssh_port = 22;
// SSH 服务器指纹
private $ssh_server_fp = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// SSH 用户名
private $ssh_auth_user = 'username';
// SSH 公钥文件
private $ssh_auth_pub = '/home/username/.ssh/id_rsa.pub';
// SSH 私钥文件
private $ssh_auth_priv = '/home/username/.ssh/id_rsa';
// SSH 私钥密码(null == 无密码)
private $ssh_auth_pass;
// SSH 连接
private $connection;
public function connect() {
if (!($this->connection = ssh2_connect($this->ssh_host, $this->ssh_port))) {
throw new Exception('无法连接到服务器');
}
$fingerprint = ssh2_fingerprint($this->connection, SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);
if (strcmp($this->ssh_server_fp, $fingerprint) !== 0) {
throw new Exception('无法验证服务器身份!');
}
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('服务器拒绝认证');
}
}
public function exec($cmd) {
if (!($stream = ssh2_exec($this->connection, $cmd))) {
throw new Exception('SSH 命令执行失败');
}
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();
}
}
?>
[EDIT BY danbrown AT php DOT net: Contains two bugfixes suggested by 'AlainC' in user note #109185 (removed) on 26-JUN-2012.]