必备条件
1. 服务器之间的密钥认证(使用apache运行用户进行认证)
2. PHP安装ssh2扩展
若使用root用户认证,该类可执行除交互以外的所有Linux命令,谨慎操作!!
<?php
class SSHExec{
private $host_ip;//执行shell的节点ip
private $ssh2_conn;//ssh2连接
private $public_key = '/home/apache/.ssh/id_rsa.pub';//公钥路径,根据实际情况进行设置
private $private_key = '/home/apache/.ssh/id_rsa';//私钥路径,根据实际情况进行设置
public function __construct($host_ip){
$this->host_ip = $host_ip;
}
//传入shell命令即可
public function ssh2exec($cmd) {
if (!$this->connection_ssh2()){
throw new Exception("connection_ssh2 Failed");
}
$stream = ssh2_exec($this->ssh2_conn, $cmd);
stream_set_blocking($stream, true);
return (stream_get_contents($stream));
}
private function connection_ssh2() {
if ($this->ssh2_conn) return $this->ssh2_conn;
if (!($this->ssh2_conn = ssh2_connect($this->host_ip, 22, array('hostkey' => 'ssh-rsa')))) {
throw new Exception("Connect SSH [FAILED]\n");
}
// echo "Connect SSH [OK]\n";
if (ssh2_auth_pubkey_file($this->ssh2_conn, 'root', $this->public_key, $this->private_key, 'secret')) {
//echo "Public Key Authentication Successful\n";
} else {
throw new Exception('Public Key Authentication Failed');
}
return $this->ssh2_conn;
}
}
$ssh = new SSHExec("192.168.2.106");
echo "<pre>";
echo $ssh->ssh2exec("df -h");
echo "========================================================<br>";
echo $ssh->ssh2exec("cat /proc/cpuinfo");
echo "</pre>";
以上代码执行结果