使用上节安装的 ssh2 扩展来操作 ssh
https://blog.binger.site/?p=1285

代码

来着php.net http://php.net/manual/zh/function.ssh2-connect.php#104758

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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();
}
}