由于缺少完整的示例,这里提供了一个简单的 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();
}
}
?>
[由 php DOT net 上的 danbrown 编辑:包含 'AlainC' 在用户注释 #109185(已删除)中于 2012 年 6 月 26 日建议的两个错误修复。]