【PHP】 让PHP执行Linux命令

必备条件

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>";


以上代码执行结果



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值